This file is indexed.

/usr/lib/python2.7/dist-packages/paraview/simple.py is in paraview-python 4.0.1-1ubuntu1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
r"""simple is a module for using paraview server manager in Python. It
provides a simple convenience layer to functionality provided by the
C++ classes wrapped to Python as well as the servermanager module.

A simple example::

  from paraview.simple import *

  # Create a new sphere proxy on the active connection and register it
  # in the sources group.
  sphere = Sphere(ThetaResolution=16, PhiResolution=32)

  # Apply a shrink filter
  shrink = Shrink(sphere)

  # Turn the visiblity of the shrink object on.
  Show(shrink)

  # Render the scene
  Render()

"""
#==============================================================================
#
#  Program:   ParaView
#  Module:    simple.py
#
#  Copyright (c) Kitware, Inc.
#  All rights reserved.
#  See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
#
#     This software is distributed WITHOUT ANY WARRANTY; without even
#     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
#     PURPOSE.  See the above copyright notice for more information.
#
#==============================================================================

import paraview
paraview.compatibility.major = 3
paraview.compatibility.minor = 5
import servermanager

#==============================================================================
# Client/Server Connection methods
#==============================================================================

def Disconnect(ns=None, force=True):
    """Free the current active session"""
    if not ns:
        ns = globals()

    supports_simutaneous_connections =\
        servermanager.vtkProcessModule.GetProcessModule().GetMultipleSessionsSupport()
    if not force and supports_simutaneous_connections:
        # This is an internal Disconnect request that doesn't need to happen in
        # multi-server setup. Ignore it.
        return
    if servermanager.ActiveConnection:
        _remove_functions(ns)
        servermanager.Disconnect()
        import gc
        gc.collect()

# -----------------------------------------------------------------------------

def Connect(ds_host=None, ds_port=11111, rs_host=None, rs_port=11111):
    """Creates a connection to a server. Example usage::

    > Connect("amber") # Connect to a single server at default port
    > Connect("amber", 12345) # Connect to a single server at port 12345
    > Connect("amber", 11111, "vis_cluster", 11111) # connect to data server, render server pair"""
    Disconnect(globals(), False)
    connection = servermanager.Connect(ds_host, ds_port, rs_host, rs_port)
    _add_functions(globals())
    _CreateEssentialProxies()
    return connection

# -----------------------------------------------------------------------------

def ReverseConnect(port=11111):
    """Create a reverse connection to a server.  Listens on port and waits for
    an incoming connection from the server."""
    Disconnect(globals(), False)
    connection = servermanager.ReverseConnect(port)
    _add_functions(globals())
    _CreateEssentialProxies()
    return connection

#==============================================================================
# Multi-servers
#==============================================================================

def SetActiveConnection(connection=None, ns=None):
    """Set the active connection. If the process was run without multi-server
       enabled and this method is called with a non-None argument while an
       ActiveConnection is present, it will raise a RuntimeError."""
    if not ns:
        ns = globals()
    if servermanager.ActiveConnection != connection:
        _remove_functions(ns)
        servermanager.SetActiveConnection(connection)
        _add_functions(ns)

#==============================================================================
# Views and Layout methods
#==============================================================================

def CreateView(view_xml_name):
    "Creates and returns the specified proxy view based on its name/label."
    view = servermanager._create_view(view_xml_name)
    servermanager.ProxyManager().RegisterProxy("views", \
      "my_view%d" % _funcs_internals.view_counter, view)
    active_objects.view = view
    _funcs_internals.view_counter += 1

    tk = servermanager.ProxyManager().GetProxiesInGroup("timekeeper").values()[0]
    views = tk.Views
    if not view in views:
        views.append(view)
    try:
        scene = GetAnimationScene()
        if not view in scene.ViewModules:
            scene.ViewModules.append(view)
    except servermanager.MissingProxy:
        pass
    return view

# -----------------------------------------------------------------------------

def CreateRenderView():
    """"Create standard 3D render view"""
    return CreateView("RenderView")

# -----------------------------------------------------------------------------

def CreateXYPlotView():
    """Create XY plot Chart view"""
    return CreateView("XYChartView")

# -----------------------------------------------------------------------------

def CreateBarChartView():
    """"Create Bar Chart view"""
    return CreateView("XYBarChartView")

# -----------------------------------------------------------------------------

def CreateComparativeRenderView():
    """"Create Comparative view"""
    return CreateView("ComparativeRenderView")

# -----------------------------------------------------------------------------

def CreateComparativeXYPlotView():
    """"Create comparative XY plot Chart view"""
    return CreateView("ComparativeXYPlotView")

# -----------------------------------------------------------------------------

def CreateComparativeBarChartView():
    """"Create comparative Bar Chart view"""
    return CreateView("ComparativeBarChartView")

# -----------------------------------------------------------------------------

def CreateParallelCoordinatesChartView():
    """"Create Parallele coordinate Chart view"""
    return CreateView("ParallelCoordinatesChartView")

# -----------------------------------------------------------------------------

def Create2DRenderView():
    """"Create the standard 3D render view with the 2D interaction mode turned ON"""
    return CreateView("2DRenderView")

# -----------------------------------------------------------------------------

def GetRenderView():
    "Returns the active view if there is one. Else creates and returns a new view."
    view = active_objects.view
    if not view:
        # it's possible that there's no active view, but a render view exists.
        # If so, locate that and return it (before trying to create a new one).
        view = servermanager.GetRenderView()
    if not view:
        view = CreateRenderView()
    return view

# -----------------------------------------------------------------------------

def GetRenderViews():
    "Returns all render views as a list."
    return servermanager.GetRenderViews()

# -----------------------------------------------------------------------------

def SetViewProperties(view=None, **params):
    """Sets one or more properties of the given view. If an argument
    is not provided, the active view is used. Pass a list of property_name=value
    pairs to this function to set property values. For example::

        SetProperties(Background=[1, 0, 0], UseImmediateMode=0)
    """
    if not view:
        view = active_objects.view
    SetProperties(view, **params)

# -----------------------------------------------------------------------------

def Render(view=None):
    """Renders the given view (default value is active view)"""
    if not view:
        view = active_objects.view
    view.StillRender()
    if _funcs_internals.first_render:
        # Not all views have a ResetCamera method
        try:
            view.ResetCamera()
            view.StillRender()
        except AttributeError: pass
        _funcs_internals.first_render = False
    return view

# -----------------------------------------------------------------------------

def ResetCamera(view=None):
    """Resets the settings of the camera to preserver orientation but include
    the whole scene. If an argument is not provided, the active view is
    used."""
    if not view:
        view = active_objects.view
    if hasattr(view, "ResetCamera"):
        view.ResetCamera()
    if hasattr(view, "ResetDisplay"):
        view.ResetDisplay()
    Render(view)

# -----------------------------------------------------------------------------

def GetLayouts():
    """Returns the layout proxies on the active session.
    Layout proxies are used to place views in a grid."""
    return servermanager.ProxyManager().GetProxiesInGroup("layouts")

# -----------------------------------------------------------------------------

def GetLayout(view=None):
    """Return the layout containing the give view, if any.
    If no view is specified, active view is used.
    """
    if not view:
        view = GetActiveView()
    if not view:
        raise RuntimeError, "No active view was found."
    layouts = GetLayouts()
    for layout in layouts.values():
        if layout.GetViewLocation(view) != -1:
            return layout
    return None

#==============================================================================
# Representation methods
#==============================================================================

def GetRepresentation(proxy=None, view=None):
    """"Given a pipeline object and view, returns the corresponding representation object.
    If pipeline object and view are not specified, active objects are used."""
    if not view:
        view = active_objects.view
    if not proxy:
        proxy = active_objects.source
    rep = servermanager.GetRepresentation(proxy, view)
    if not rep:
        rep = servermanager.CreateRepresentation(proxy, view)
        servermanager.ProxyManager().RegisterProxy("representations", \
          "my_representation%d" % _funcs_internals.rep_counter, rep)
        _funcs_internals.rep_counter += 1
    return rep

# -----------------------------------------------------------------------------

def GetDisplayProperties(proxy=None, view=None):
    """"Given a pipeline object and view, returns the corresponding representation object.
    If pipeline object and/or view are not specified, active objects are used."""
    return GetRepresentation(proxy, view)

# -----------------------------------------------------------------------------

def Show(proxy=None, view=None, **params):
    """Turns the visibility of a given pipeline object on in the given view.
    If pipeline object and/or view are not specified, active objects are used."""
    if proxy == None:
        proxy = GetActiveSource()
    if proxy == None:
        raise RuntimeError, "Show() needs a proxy argument or that an active source is set."
    if not view and not active_objects.view:
        CreateRenderView()
    rep = GetDisplayProperties(proxy, view)
    if rep == None:
        raise RuntimeError, "Could not create a representation object for proxy %s" % proxy.GetXMLLabel()
    for param in params.keys():
        setattr(rep, param, params[param])
    rep.Visibility = 1
    return rep

# -----------------------------------------------------------------------------

def Hide(proxy=None, view=None):
    """Turns the visibility of a given pipeline object off in the given view.
    If pipeline object and/or view are not specified, active objects are used."""
    rep = GetDisplayProperties(proxy, view)
    rep.Visibility = 0

# -----------------------------------------------------------------------------

def SetDisplayProperties(proxy=None, view=None, **params):
    """Sets one or more display properties of the given pipeline object. If an argument
    is not provided, the active source is used. Pass a list of property_name=value
    pairs to this function to set property values. For example::

        SetProperties(Color=[1, 0, 0], LineWidth=2)
    """
    rep = GetDisplayProperties(proxy, view)
    SetProperties(rep, **params)

# -----------------------------------------------------------------------------

def _DisableFirstRenderCameraReset():
    """Disable the first render camera reset.  Normally a ResetCamera is called
    automatically when Render is called for the first time after importing
    this module."""
    _funcs_internals.first_render = False

#==============================================================================
# Proxy handling methods
#==============================================================================

def SetProperties(proxy=None, **params):
    """Sets one or more properties of the given pipeline object. If an argument
    is not provided, the active source is used. Pass a list of property_name=value
    pairs to this function to set property values. For example::

        SetProperties(Center=[1, 2, 3], Radius=3.5)
    """
    if not proxy:
        proxy = active_objects.source
    for param in params.keys():
        if not hasattr(proxy, param):
            raise AttributeError("object has no property %s" % param)
        setattr(proxy, param, params[param])

# -----------------------------------------------------------------------------

def GetProperty(*arguments, **keywords):
    """Get one property of the given pipeline object. If keywords are used,
       you can set the proxy and the name of the property that you want to get
       like in the following example::

            GetProperty({proxy=sphere, name="Radius"})

       If it's arguments that are used, then you have two case:
         - if only one argument is used that argument will be
           the property name.
         - if two arguments are used then the first one will be
           the proxy and the second one the property name.
       Several example are given below::

           GetProperty({name="Radius"})
           GetProperty({proxy=sphereProxy, name="Radius"})
           GetProperty( sphereProxy, "Radius" )
           GetProperty( "Radius" )
    """
    name = None
    proxy = None
    for key in keywords:
        if key == "name":
            name = keywords[key]
        if key == "proxy":
            proxy = keywords[key]
    if len(arguments) == 1 :
        name = arguments[0]
    if len(arguments) == 2 :
        proxy = arguments[0]
        name  = arguments[1]
    if not name:
        raise RuntimeError, "Expecting at least a property name as input. Otherwise keyword could be used to set 'proxy' and property 'name'"
    if not proxy:
        proxy = active_objects.source
    return proxy.GetProperty(name)

#==============================================================================
# ServerManager methods
#==============================================================================

def RenameSource(newName, proxy=None):
    """Renames the given source.  If the given proxy is not registered
    in the sources group this method will have no effect.  If no source is
    provided, the active source is used."""
    if not proxy:
        proxy = active_objects.source
    pxm = servermanager.ProxyManager()
    oldName = pxm.GetProxyName("sources", proxy)
    if oldName:
      pxm.RegisterProxy("sources", newName, proxy)
      pxm.UnRegisterProxy("sources", oldName, proxy)

# -----------------------------------------------------------------------------

def FindSource(name):
    """
    Return a proxy base on the name that was used to register it
    into the ProxyManager.
    Example usage::

       Cone(guiName='MySuperCone')
       Show()
       Render()
       myCone = FindSource('MySuperCone')
    """
    return servermanager.ProxyManager().GetProxy("sources", name)

# -----------------------------------------------------------------------------

def GetSources():
    """Given the name of a source, return its Python object."""
    return servermanager.ProxyManager().GetProxiesInGroup("sources")

# -----------------------------------------------------------------------------

def GetRepresentations():
    """Returns all representations (display properties)."""
    return servermanager.ProxyManager().GetProxiesInGroup("representations")

# -----------------------------------------------------------------------------

def UpdatePipeline(time=None, proxy=None):
    """Updates (executes) the given pipeline object for the given time as
    necessary (i.e. if it did not already execute). If no source is provided,
    the active source is used instead."""
    if not proxy:
        proxy = active_objects.source
    if time:
        proxy.UpdatePipeline(time)
    else:
        proxy.UpdatePipeline()

# -----------------------------------------------------------------------------

def Delete(proxy=None):
    """Deletes the given pipeline object or the active source if no argument
    is specified."""
    if not proxy:
        proxy = active_objects.source
    # Unregister any helper proxies stored by a vtkSMProxyListDomain
    for prop in proxy:
        listdomain = prop.GetDomain('proxy_list')
        if listdomain:
            if listdomain.GetClassName() != 'vtkSMProxyListDomain':
                continue
            group = "pq_helper_proxies." + proxy.GetGlobalIDAsString()
            for i in xrange(listdomain.GetNumberOfProxies()):
                pm = servermanager.ProxyManager()
                iproxy = listdomain.GetProxy(i)
                name = pm.GetProxyName(group, iproxy)
                if iproxy and name:
                    pm.UnRegisterProxy(group, name, iproxy)

    # Remove source/view from time keeper
    tk = servermanager.ProxyManager().GetProxiesInGroup("timekeeper").values()[0]
    if isinstance(proxy, servermanager.SourceProxy):
        try:
            idx = tk.TimeSources.index(proxy)
            del tk.TimeSources[idx]
        except ValueError:
            pass
    else:
        try:
            idx = tk.Views.index(proxy)
            del tk.Views[idx]
        except ValueError:
            pass
    servermanager.UnRegister(proxy)

    # If this is a representation, remove it from all views.
    if proxy.SMProxy.IsA("vtkSMRepresentationProxy") or \
        proxy.SMProxy.IsA("vtkSMNewWidgetRepresentationProxy"):
        for view in GetRenderViews():
            view.Representations.remove(proxy)
    # If this is a source, remove the representation iff it has no consumers
    # Also change the active source if necessary
    elif proxy.SMProxy.IsA("vtkSMSourceProxy"):
        sources = servermanager.ProxyManager().GetProxiesInGroup("sources")
        for i in range(proxy.GetNumberOfConsumers()):
            if proxy.GetConsumerProxy(i) in sources:
                raise RuntimeError("Source has consumers. It cannot be deleted " +
                  "until all consumers are deleted.")
        if proxy == GetActiveSource():
            if hasattr(proxy, "Input") and proxy.Input:
                if isinstance(proxy.Input, servermanager.Proxy):
                    SetActiveSource(proxy.Input)
                else:
                    SetActiveSource(proxy.Input[0])
            else: SetActiveSource(None)
        for rep in GetRepresentations().values():
            if rep.Input == proxy:
                Delete(rep)
    # Change the active view if necessary
    elif proxy.SMProxy.IsA("vtkSMRenderViewProxy"):
        if proxy == GetActiveView():
            if len(GetRenderViews()) > 0:
                SetActiveView(GetRenderViews()[0])
            else:
                SetActiveView(None)

#==============================================================================
# Active Source / View / Camera / AnimationScene
#==============================================================================

def GetActiveView():
    """.. _GetActiveView:
        Returns the active view."""
    return active_objects.view

# -----------------------------------------------------------------------------

def SetActiveView(view):
    """.. _SetActiveView:
        Sets the active view."""
    active_objects.view = view

# -----------------------------------------------------------------------------

def GetActiveSource():
    """.. _GetActiveSource:
        Returns the active source."""
    return active_objects.source

# -----------------------------------------------------------------------------

def SetActiveSource(source):
    """.. _SetActiveSource:
        Sets the active source."""
    active_objects.source = source

# -----------------------------------------------------------------------------

def GetActiveCamera():
    """Returns the active camera for the active view. The returned object
    is an instance of vtkCamera."""
    return GetActiveView().GetActiveCamera()

#==============================================================================
# I/O methods
#==============================================================================

def OpenDataFile(filename, **extraArgs):
    """Creates a reader to read the give file, if possible.
       This uses extension matching to determine the best reader possible.
       If a reader cannot be identified, then this returns None."""
    session = servermanager.ActiveConnection.Session
    reader_factor = servermanager.vtkSMProxyManager.GetProxyManager().GetReaderFactory()
    if reader_factor.GetNumberOfRegisteredPrototypes() == 0:
      reader_factor.RegisterPrototypes(session, "sources")
    first_file = filename
    if type(filename) == list:
        first_file = filename[0]
    if not reader_factor.TestFileReadability(first_file, session):
        msg = "File not readable: %s " % first_file
        raise RuntimeError, msg
    if not reader_factor.CanReadFile(first_file, session):
        msg = "File not readable. No reader found for '%s' " % first_file
        raise RuntimeError, msg
    prototype = servermanager.ProxyManager().GetPrototypeProxy(
      reader_factor.GetReaderGroup(), reader_factor.GetReaderName())
    xml_name = paraview.make_name_valid(prototype.GetXMLLabel())
    reader_func = _create_func(xml_name, servermanager.sources)
    pname = servermanager.vtkSMCoreUtilities.GetFileNameProperty(prototype)
    if pname:
        extraArgs[pname] = filename
        reader = reader_func(**extraArgs)
    return reader

# -----------------------------------------------------------------------------

def CreateWriter(filename, proxy=None, **extraArgs):
    """Creates a writer that can write the data produced by the source proxy in
       the given file format (identified by the extension). If no source is
       provided, then the active source is used. This doesn't actually write the
       data, it simply creates the writer and returns it."""
    if not filename:
       raise RuntimeError, "filename must be specified"
    session = servermanager.ActiveConnection.Session
    writer_factory = servermanager.vtkSMProxyManager.GetProxyManager().GetWriterFactory()
    if writer_factory.GetNumberOfRegisteredPrototypes() == 0:
        writer_factory.RegisterPrototypes(session, "writers")
    if not proxy:
        proxy = GetActiveSource()
    if not proxy:
        raise RuntimeError, "Could not locate source to write"
    writer_proxy = writer_factory.CreateWriter(filename, proxy.SMProxy, proxy.Port)
    return servermanager._getPyProxy(writer_proxy)

# -----------------------------------------------------------------------------

def WriteImage(filename, view=None, **params):
    """Saves the given view (or the active one if none is given) as an
    image. Optionally, you can specify the writer and the magnification
    using the Writer and Magnification named arguments. For example::

        WriteImage("foo.mypng", aview, Writer=vtkPNGWriter, Magnification=2)

    If no writer is provided, the type is determined from the file extension.
    Currently supported extensions are png, bmp, ppm, tif, tiff, jpg and jpeg.
    The writer is a VTK class that is capable of writing images.
    Magnification is used to determine the size of the written image. The size
    is obtained by multiplying the size of the view with the magnification.
    Rendering may be done using tiling to obtain the correct size without
    resizing the view."""
    if not view:
        view = active_objects.view
    writer = None
    if params.has_key('Writer'):
        writer = params['Writer']
    mag = 1
    if params.has_key('Magnification'):
        mag = int(params['Magnification'])
    if not writer:
        writer = _find_writer(filename)
    view.WriteImage(filename, writer, mag)

# -----------------------------------------------------------------------------

def WriteAnimation(filename, **params):
    """Writes the current animation as a file. Optionally one can specify
    arguments that qualify the saved animation files as keyword arguments.
    Accepted options are as follows:

    * **Magnification** *(integer)* : set the maginification factor for the saved
      animation.
    * **Quality** *(0 [worst] or 1 or 2 [best])* : set the quality of the generated
      movie (if applicable).
    * **Subsampling** *(integer)* : setting whether the movie encoder should use
      subsampling of the chrome planes or not, if applicable. Since the human
      eye is more sensitive to brightness than color variations, subsampling
      can be useful to reduce the bitrate. Default value is 0.
    * **BackgroundColor** *(3-tuple of doubles)* : set the RGB background color to
      use to fill empty spaces in the image.
    * **FrameRate** *(double)*: set the frame rate (if applicable).
    * **StartFileCount** *(int)*: set the first number used for the file name
      (23 => i.e. image-0023.png).
    * **PlaybackTimeWindow** *([double, double])*: set the time range that
      should be used to play a subset of the total animation time.
      (By default the whole application will play).
    """
    scene = GetAnimationScene()
    # ensures that the TimeKeeper track is created.
    GetTimeTrack()
    iw = servermanager.vtkSMAnimationSceneImageWriter()
    iw.SetAnimationScene(scene.SMProxy)
    iw.SetFileName(filename)
    if params.has_key("Magnification"):
        iw.SetMagnification(int(params["Magnification"]))
    if params.has_key("Quality"):
        iw.SetQuality(int(params["Quality"]))
    if params.has_key("Subsampling"):
        iw.SetSubsampling(int(params["Subsampling"]))
    if params.has_key("BackgroundColor"):
        iw.SetBackgroundColor(params["BackgroundColor"])
    if params.has_key("FrameRate"):
        iw.SetFrameRate(float(params["FrameRate"]))
    iw.Save()

#==============================================================================
# Lookup Table / Scalarbar methods
#==============================================================================

def CreateLookupTable(**params):
    """Create and return a lookup table.  Optionally, parameters can be given
    to assign to the lookup table.
    """
    lt = servermanager.rendering.PVLookupTable()
    servermanager.Register(lt)
    SetProperties(lt, **params)
    return lt

# -----------------------------------------------------------------------------

def CreatePiecewiseFunction(**params):
    """Create and return a piecewise function.  Optionally, parameters can be
    given to assign to the piecewise function.
    """
    pfunc = servermanager.piecewise_functions.PiecewiseFunction()
    servermanager.Register(pfunc)
    SetProperties(pfunc, **params)
    return pfunc

# -----------------------------------------------------------------------------

def GetLookupTableForArray(arrayname, num_components, **params):
    """Used to get an existing lookuptable for a array or to create one if none
    exists. Keyword arguments can be passed in to initialize the LUT if a new
    one is created."""
    proxyName = "%d.%s.PVLookupTable" % (int(num_components), arrayname)
    lut = servermanager.ProxyManager().GetProxy("lookup_tables", proxyName)
    if lut:
        return lut
    # No LUT exists for this array, create a new one.
    # TODO: Change this to go a LookupTableManager that is shared with the GUI,
    # so that the GUI and python end up create same type of LUTs. For now,
    # python will create a Blue-Red LUT, unless overridden by params.
    lut = servermanager.rendering.PVLookupTable(
            ColorSpace="HSV", RGBPoints=[0, 0, 0, 1, 1, 1, 0, 0])
    SetProperties(lut, **params)
    servermanager.Register(lut, registrationName=proxyName)
    return lut

# -----------------------------------------------------------------------------

def CreateScalarBar(**params):
    """Create and return a scalar bar widget.  The returned widget may
    be added to a render view by appending it to the view's representations
    The widget must have a valid lookup table before it is added to a view.
    It is possible to pass the lookup table (and other properties) as arguments
    to this method::

        lt = MakeBlueToRedLt(3.5, 7.5)
        bar = CreateScalarBar(LookupTable=lt, Title="Velocity")
        GetRenderView().Representations.append(bar)

    By default the returned widget is selectable and resizable.
    """
    sb = servermanager.rendering.ScalarBarWidgetRepresentation()
    servermanager.Register(sb)
    sb.Selectable = 1
    sb.Resizable = 1
    sb.Enabled = 1
    sb.Title = "Scalars"
    SetProperties(sb, **params)
    return sb

# -----------------------------------------------------------------------------

# TODO: Change this to take the array name and number of components. Register
# the lt under the name ncomp.array_name
def MakeBlueToRedLT(min, max):
    """
    Create a LookupTable that go from blue to red using the scalar range
    provided by the min and max arguments.
    """
    # Define RGB points. These are tuples of 4 values. First one is
    # the scalar values, the other 3 the RGB values.
    rgbPoints = [min, 0, 0, 1, max, 1, 0, 0]
    return CreateLookupTable(RGBPoints=rgbPoints, ColorSpace="HSV")

#==============================================================================
# CameraLink methods
#==============================================================================

def AddCameraLink(viewProxy, viewProxyOther, linkName):
    """Create a camera link between two view proxies.  A name must be given
    so that the link can be referred to by name.  If a link with the given
    name already exists it will be removed first."""
    if not viewProxyOther: viewProxyOther = GetActiveView()
    link = servermanager.vtkSMCameraLink()
    link.AddLinkedProxy(viewProxy.SMProxy, 1)
    link.AddLinkedProxy(viewProxyOther.SMProxy, 2)
    link.AddLinkedProxy(viewProxyOther.SMProxy, 1)
    link.AddLinkedProxy(viewProxy.SMProxy, 2)
    RemoveCameraLink(linkName)
    servermanager.ProxyManager().RegisterLink(linkName, link)

# -----------------------------------------------------------------------------

def RemoveCameraLink(linkName):
    """Remove a camera link with the given name."""
    servermanager.ProxyManager().UnRegisterLink(linkName)

#==============================================================================
# Animation methods
#==============================================================================

def GetAnimationScene():
    """Returns the application-wide animation scene. ParaView has only one
    global animation scene. This method provides access to that. Users are
    free to create additional animation scenes directly, but those scenes
    won't be shown in the ParaView GUI."""
    animation_proxies = servermanager.ProxyManager().GetProxiesInGroup("animation")
    scene = None
    for aProxy in animation_proxies.values():
        if aProxy.GetXMLName() == "AnimationScene":
            scene = aProxy
            break
    if not scene:
        raise servermanager.MissingProxy, "Could not locate global AnimationScene."
    return scene

# -----------------------------------------------------------------------------

def AnimateReader(reader=None, view=None, filename=None):
    """This is a utility function that, given a reader and a view
    animates over all time steps of the reader. If the optional
    filename is provided, a movie is created (type depends on the
    extension of the filename."""
    if not reader:
        reader = active_objects.source
    if not view:
        view = active_objects.view

    return servermanager.AnimateReader(reader, view, filename)

# -----------------------------------------------------------------------------

def _GetRepresentationAnimationHelper(sourceproxy):
    """Internal method that returns the representation animation helper for a
       source proxy. It creates a new one if none exists."""
    # ascertain that proxy is a source proxy
    if not sourceproxy in GetSources().values():
        return None
    for proxy in servermanager.ProxyManager():
        if proxy.GetXMLName() == "RepresentationAnimationHelper" and\
           proxy.GetProperty("Source").IsProxyAdded(sourceproxy.SMProxy):
             return proxy
    # create a new helper
    proxy = servermanager.misc.RepresentationAnimationHelper(
      Source=sourceproxy)
    servermanager.ProxyManager().RegisterProxy(
      "pq_helper_proxies.%s" % sourceproxy.GetGlobalIDAsString(),
      "RepresentationAnimationHelper", proxy)
    return proxy

# -----------------------------------------------------------------------------

def GetAnimationTrack(propertyname_or_property, index=None, proxy=None):
    """Returns an animation cue for the property. If one doesn't exist then a
    new one will be created.
    Typical usage::

      track = GetAnimationTrack("Center", 0, sphere) or
      track = GetAnimationTrack(sphere.GetProperty("Radius")) or

      # this returns the track to animate visibility of the active source in
      # all views.
      track = GetAnimationTrack("Visibility")

    For animating properties on implicit planes etc., use the following
    signatures::

      track = GetAnimationTrack(slice.SliceType.GetProperty("Origin"), 0) or
      track = GetAnimationTrack("Origin", 0, slice.SliceType)
    """
    if not proxy:
        proxy = GetActiveSource()
    if not isinstance(proxy, servermanager.Proxy):
        raise TypeError, "proxy must be a servermanager.Proxy instance"
    if isinstance(propertyname_or_property, str):
        propertyname = propertyname_or_property
    elif isinstance(propertyname_or_property, servermanager.Property):
        prop = propertyname_or_property
        propertyname = prop.Name
        proxy = prop.Proxy
    else:
        raise TypeError, "propertyname_or_property must be a string or servermanager.Property"

    # To handle the case where the property is actually a "display" property, in
    # which case we are actually animating the "RepresentationAnimationHelper"
    # associated with the source.
    if propertyname in ["Visibility", "Opacity"]:
        proxy = _GetRepresentationAnimationHelper(proxy)
    if not proxy or not proxy.GetProperty(propertyname):
        raise AttributeError, "Failed to locate property %s" % propertyname

    scene = GetAnimationScene()
    for cue in scene.Cues:
        try:
            if cue.AnimatedProxy == proxy and\
               cue.AnimatedPropertyName == propertyname:
                if index == None or index == cue.AnimatedElement:
                    return cue
        except AttributeError:
            pass

    # matching animation track wasn't found, create a new one.
    cue = KeyFrameAnimationCue()
    cue.AnimatedProxy = proxy
    cue.AnimatedPropertyName = propertyname
    if index != None:
        cue.AnimatedElement = index
    scene.Cues.append(cue)
    return cue

# -----------------------------------------------------------------------------

def GetCameraTrack(view=None):
    """Returns the camera animation track for the given view. If no view is
    specified, active view will be used. If no exisiting camera animation track
    is found, a new one will be created."""
    if not view:
        view = GetActiveView()
    if not view:
        raise ValueError, "No view specified"
    scene = GetAnimationScene()
    for cue in scene.Cues:
        if cue.AnimatedProxy == view and\
           cue.GetXMLName() == "CameraAnimationCue":
            return cue
    # no cue was found, create a new one.
    cue = CameraAnimationCue()
    cue.AnimatedProxy = view
    scene.Cues.append(cue)
    return cue

# -----------------------------------------------------------------------------

def GetTimeTrack():
    """Returns the animation track used to control the time requested from all
    readers/filters during playback.
    This is the "TimeKeeper - Time" track shown in ParaView's 'Animation View'.
    If none exists, a new one will be created."""
    scene = GetAnimationScene()
    tk = scene.TimeKeeper
    for cue in scene.Cues:
        if cue.GetXMLName() == "TimeAnimationCue" and cue.AnimatedProxy == tk\
            and cue.AnimatedPropertyName == "Time":
            return cue
    # no cue was found, create a new one.
    cue = TimeAnimationCue()
    cue.AnimatedProxy = tk
    cue.AnimatedPropertyName = "Time"
    scene.Cues.append(cue)
    return cue

#==============================================================================
# Plugin Management
#==============================================================================

def LoadXML(xmlstring, ns=None):
    """Given a server manager XML as a string, parse and process it.
    If you loaded the simple module with from paraview.simple import *,
    make sure to pass globals() as the second arguments:
    LoadXML(xmlstring, globals())
    Otherwise, the new functions will not appear in the global namespace."""
    if not ns:
        ns = globals()
    servermanager.LoadXML(xmlstring)
    _add_functions(ns)

# -----------------------------------------------------------------------------

def LoadPlugin(filename, remote=True, ns=None):
    """Loads a ParaView plugin and updates this module with new constructors
    if any. The remote argument (default to True) is to specify whether
    the plugin will be loaded on client (remote=False) or on server (remote=True).
    If you loaded the simple module with from paraview.simple import *,
    make sure to pass globals() as an argument::

        LoadPlugin("myplugin", False, globals()) # to load on client
        LoadPlugin("myplugin", True, globals())  # to load on server
        LoadPlugin("myplugin", ns=globals())     # to load on server

    Otherwise, the new functions will not appear in the global namespace."""

    if not ns:
        ns = globals()
    servermanager.LoadPlugin(filename, remote)
    _add_functions(ns)

# -----------------------------------------------------------------------------

def LoadDistributedPlugin(pluginname, remote=True, ns=None):
    """Loads a plugin that's distributed with the executable. This uses the
    information known about plugins distributed with ParaView to locate the
    shared library for the plugin to load. Raises a RuntimeError if the plugin
    was not found."""
    if not servermanager.ActiveConnection:
        raise RuntimeError, "Cannot load a plugin without a session."
    plm = servermanager.vtkSMProxyManager.GetProxyManager().GetPluginManager()
    if remote:
        session = servermanager.ActiveConnection.Session
        info = plm.GetRemoteInformation(session)
    else:
        info = plm.GetLocalInformation()
    for cc in range(0, info.GetNumberOfPlugins()):
        if info.GetPluginName(cc) == pluginname:
            return LoadPlugin(info.GetPluginFileName(cc), remote, ns)
    raise RuntimeError, "Plugin '%s' not found" % pluginname

#==============================================================================
# Selection Management
#==============================================================================

def SelectCells(query=None, proxy=None):
    """Select cells satisfying the query. If query is None, then all cells are
       selected. If proxy is None, then the active source is used."""
    if not proxy:
        proxy = GetActiveSource()
    if not proxy:
        raise RuntimeError, "No active source was found."

    if not query:
        # This ends up being true for all cells.
        query = "id >= 0"

    # Note, selSource is not registered with the proxy manager.
    selSource = servermanager.sources.SelectionQuerySource()
    selSource.FieldType = "CELL"
    selSource.QueryString = str(query)
    proxy.SMProxy.SetSelectionInput(proxy.Port, selSource.SMProxy, 0)
    return selSource

# -----------------------------------------------------------------------------

def ClearSelection(proxy=None):
    """Clears the selection on the active source."""
    if not proxy:
        proxy = GetActiveSource()
    if not proxy:
        raise RuntimeError, "No active source was found."
    proxy.SMProxy.SetSelectionInput(proxy.Port, None, 0)

#==============================================================================
# Usage and demo code set
#==============================================================================

def demo1():
    """
    Simple demo that create the following pipeline::

       sphere - shrink +
       cone            + > append

    """
    # Create a sphere of radius = 2, theta res. = 32
    # This object becomes the active source.
    ss = Sphere(Radius=2, ThetaResolution=32)
    # Apply the shrink filter. The Input property is optional. If Input
    # is not specified, the filter is applied to the active source.
    shr = Shrink(Input=ss)
    # Create a cone source.
    cs = Cone()
    # Append cone and shrink
    app = AppendDatasets()
    app.Input = [shr, cs]
    # Show the output of the append filter. The argument is optional
    # as the app filter is now the active object.
    Show(app)
    # Render the default view.
    Render()

# -----------------------------------------------------------------------------

def demo2(fname="/Users/berk/Work/ParaView/ParaViewData/Data/disk_out_ref.ex2"):
    """This demo shows the use of readers, data information and display
    properties."""

    # Create the exodus reader and specify a file name
    reader = ExodusIIReader(FileName=fname)
    # Get the list of point arrays.
    avail = reader.PointVariables.Available
    print avail
    # Select all arrays
    reader.PointVariables = avail

    # Turn on the visibility of the reader
    Show(reader)
    # Set representation to wireframe
    SetDisplayProperties(Representation = "Wireframe")
    # Black background is not pretty
    SetViewProperties(Background = [0.4, 0.4, 0.6])
    Render()
    # Change the elevation of the camera. See VTK documentation of vtkCamera
    # for camera parameters.
    # NOTE: THIS WILL BE SIMPLER
    GetActiveCamera().Elevation(45)
    Render()
    # Now that the reader executed, let's get some information about it's
    # output.
    pdi = reader[0].PointData
    # This prints a list of all read point data arrays as well as their
    # value ranges.
    print 'Number of point arrays:', len(pdi)
    for i in range(len(pdi)):
        ai = pdi[i]
        print "----------------"
        print "Array:", i, " ", ai.Name, ":"
        numComps = ai.GetNumberOfComponents()
        print "Number of components:", numComps
        for j in range(numComps):
            print "Range:", ai.GetRange(j)
    # White is boring. Let's color the geometry using a variable.
    # First create a lookup table. This object controls how scalar
    # values are mapped to colors. See VTK documentation for
    # details.
    # Map min (0.00678) to blue, max (0.0288) to red
    SetDisplayProperties(LookupTable = MakeBlueToRedLT(0.00678, 0.0288))
    # Color by point array called Pres
    SetDisplayProperties(ColorAttributeType = "POINT_DATA")
    SetDisplayProperties(ColorArrayName = "Pres")
    Render()

#==============================================================================
# Set of Internal functions
#==============================================================================

def _create_func(key, module):
    "Internal function."

    def CreateObject(*input, **params):
        """This function creates a new proxy. For pipeline objects that accept inputs,
        all non-keyword arguments are assumed to be inputs. All keyword arguments are
        assumed to be property,value pairs and are passed to the new proxy."""

        # Instantiate the actual object from the given module.
        px = module.__dict__[key]()

        # Make sure non-keyword arguments are valid
        for inp in input:
            if inp != None and not isinstance(inp, servermanager.Proxy):
                if px.GetProperty("Input") != None:
                    raise RuntimeError, "Expecting a proxy as input."
                else:
                    raise RuntimeError, "This function does not accept non-keyword arguments."

        # Assign inputs
        if px.GetProperty("Input") != None:
            if len(input) > 0:
                px.Input = input
            else:
                # If no input is specified, try the active pipeline object
                if px.GetProperty("Input").GetRepeatable() and active_objects.get_selected_sources():
                    px.Input = active_objects.get_selected_sources()
                elif active_objects.source:
                    px.Input = active_objects.source
        else:
            if len(input) > 0:
                raise RuntimeError, "This function does not expect an input."

        registrationName = None
        for nameParam in ['registrationName', 'guiName']:
          if nameParam in params:
              registrationName = params[nameParam]
              del params[nameParam]

        # Pass all the named arguments as property,value pairs
        for param in params.keys():
            setattr(px, param, params[param])

        try:
            # Register the proxy with the proxy manager.
            if registrationName:
                group, name = servermanager.Register(px, registrationName=registrationName)
            else:
                group, name = servermanager.Register(px)


            # Register pipeline objects with the time keeper. This is used to extract time values
            # from sources. NOTE: This should really be in the servermanager controller layer.
            if group == "sources":
                has_tk = True
                try:
                    tk = servermanager.ProxyManager().GetProxiesInGroup("timekeeper").values()[0]
                except IndexError:
                    has_tk = False
                if has_tk:
                    sources = tk.TimeSources
                    if not px in sources:
                        sources.append(px)

                active_objects.source = px
        except servermanager.MissingRegistrationInformation:
            pass

        return px

    return CreateObject

# -----------------------------------------------------------------------------

def _create_doc(new, old):
    "Internal function."
    import string
    res = ""
    for doc in (new, old):
        ts = []
        strpd = doc.split('\n')
        for s in strpd:
            ts.append(s.lstrip())
        res += string.join(ts)
        res += '\n'
    return res

# -----------------------------------------------------------------------------

def _func_name_valid(name):
    "Internal function."
    valid = True
    for c in name:
        if c == '(' or c ==')':
            valid = False
            break
    return valid

# -----------------------------------------------------------------------------

def _add_functions(g):
    import os
    if os.environ.has_key("PARAVIEW_DOCUMENTATION_SKIP_ADD_FUNCTIONS"):
        return
    if not servermanager.ActiveConnection:
        return

    activeModule = servermanager.ActiveConnection.Modules
    for m in [activeModule.filters, activeModule.sources,
              activeModule.writers, activeModule.animation]:
        dt = m.__dict__
        for key in dt.keys():
            cl = dt[key]
            if not isinstance(cl, str):
                if not key in g and _func_name_valid(key):
                    #print "add %s function" % key
                    g[key] = _create_func(key, m)
                    exec "g[key].__doc__ = _create_doc(m.%s.__doc__, g[key].__doc__)" % key

# -----------------------------------------------------------------------------

def _remove_functions(g):
    list = []
    if servermanager.ActiveConnection:
       list = [m for m in dir(servermanager.ActiveConnection.Modules) if m[0] != '_']

    for m in list:
        dt = servermanager.ActiveConnection.Modules.__dict__[m].__dict__
        for key in dt.keys():
            cl = dt[key]
            if not isinstance(cl, str) and g.has_key(key):
                g.pop(key)
                #print "remove %s function" % key

# -----------------------------------------------------------------------------

def _find_writer(filename):
    "Internal function."
    extension = None
    parts = filename.split('.')
    if len(parts) > 1:
        extension = parts[-1]
    else:
        raise RuntimeError, "Filename has no extension, please specify a write"

    if extension == 'png':
        return 'vtkPNGWriter'
    elif extension == 'bmp':
        return 'vtkBMPWriter'
    elif extension == 'ppm':
        return 'vtkPNMWriter'
    elif extension == 'tif' or extension == 'tiff':
        return 'vtkTIFFWriter'
    elif extension == 'jpg' or extension == 'jpeg':
        return 'vtkJPEGWriter'
    else:
        raise RuntimeError, "Cannot infer filetype from extension:", extension

# -----------------------------------------------------------------------------

def _CreateEssentialProxies():
    """Ensures that essetial proxies like TimeKeeper and AnimationScene are
       present and are created if not"""

    servermanager.ProxyManager().DisableStateUpdateNotification()
    servermanager.ProxyManager().UpdateFromRemote()
    tk = servermanager.ProxyManager().GetProxy("timekeeper", "TimeKeeper")
    if not tk:
       try:
           tk = servermanager.misc.TimeKeeper()
           servermanager.ProxyManager().RegisterProxy("timekeeper", "TimeKeeper", tk)
       except AttributeError:
           paraview.print_error("Error: Could not create TimeKeeper")

    scene = servermanager.ProxyManager().GetProxy("animation", "AnimationScene")
    if not scene:
       try:
           scene = AnimationScene()
           scene.TimeKeeper = tk
       except NameError:
           paraview.print_error("Error: Could not create AnimationScene")

    servermanager.ProxyManager().EnableStateUpdateNotification()
    servermanager.ProxyManager().TriggerStateUpdate()

# -----------------------------------------------------------------------------

def _switchToActiveConnectionCallback(caller, event):
    """Callback called when the active session/connection changes in the
        ServerManager. We update the Python state to reflect the change."""
    if servermanager:
        session = servermanager.vtkSMProxyManager.GetProxyManager().GetActiveSession()
        connection = servermanager.GetConnectionFromSession(session)
        SetActiveConnection(connection)

#==============================================================================
# Set of Internal classes
#==============================================================================

class _active_session_observer:
    def __init__(self):
        pxm = servermanager.vtkSMProxyManager.GetProxyManager()
        self.ObserverTag = pxm.AddObserver(pxm.ActiveSessionChanged,
            _switchToActiveConnectionCallback)

    def __del__(self):
        if servermanager:
            servermanager.vtkSMProxyManager.GetProxyManager().RemoveObserver(self.ObserverTag)

# -----------------------------------------------------------------------------

class _active_objects(object):
    """This class manages the active objects (source and view). The active
    objects are shared between Python and the user interface. This class
    is for internal use. Use the :ref:`SetActiveSource`,
    :ref:`GetActiveSource`, :ref:`SetActiveView`, and :ref:`GetActiveView`
    methods for setting and getting active objects."""
    def __get_selection_model(self, name, session=None):
        "Internal method."
        if session and session != servermanager.ActiveConnection.Session:
            raise RuntimeError, "Try to set an active object with invalid active connection."
        pxm = servermanager.ProxyManager(session)
        model = pxm.GetSelectionModel(name)
        if not model:
            model = servermanager.vtkSMProxySelectionModel()
            pxm.RegisterSelectionModel(name, model)
        return model

    def set_view(self, view):
        "Sets the active view."
        active_view_model = self.__get_selection_model("ActiveView")
        if view:
            active_view_model = self.__get_selection_model("ActiveView", view.GetSession())
            active_view_model.SetCurrentProxy(view.SMProxy, 0)
        else:
            active_view_model = self.__get_selection_model("ActiveView")
            active_view_model.SetCurrentProxy(None, 0)

    def get_view(self):
        "Returns the active view."
        return servermanager._getPyProxy(
            self.__get_selection_model("ActiveView").GetCurrentProxy())

    def set_source(self, source):
        "Sets the active source."
        active_sources_model = self.__get_selection_model("ActiveSources")
        if source:
            # 3 == CLEAR_AND_SELECT
            active_sources_model = self.__get_selection_model("ActiveSources", source.GetSession())
            active_sources_model.SetCurrentProxy(source.SMProxy, 3)
        else:
            active_sources_model = self.__get_selection_model("ActiveSources")
            active_sources_model.SetCurrentProxy(None, 3)

    def __convert_proxy(self, px):
        "Internal method."
        if not px:
            return None
        if px.IsA("vtkSMSourceProxy"):
            return servermanager._getPyProxy(px)
        else:
            return servermanager.OutputPort(
              servermanager._getPyProxy(px.GetSourceProxy()),
              px.GetPortIndex())

    def get_source(self):
        "Returns the active source."
        return self.__convert_proxy(
          self.__get_selection_model("ActiveSources").GetCurrentProxy())

    def get_selected_sources(self):
        "Returns the set of sources selected in the pipeline browser."
        model = self.__get_selection_model("ActiveSources")
        proxies = []
        for i in xrange(model.GetNumberOfSelectedProxies()):
            proxies.append(self.__convert_proxy(model.GetSelectedProxy(i)))
        return proxies

    view = property(get_view, set_view)
    source = property(get_source, set_source)

# -----------------------------------------------------------------------------

class _funcs_internals:
    "Internal class."
    first_render = True
    view_counter = 0
    rep_counter = 0

#==============================================================================
# Start the session and initialize the ServerManager
#==============================================================================

active_session_observer = _active_session_observer()

if not servermanager.ActiveConnection:
    Connect()
else:
    _add_functions(globals())
    _CreateEssentialProxies()

active_objects = _active_objects()