visitmodule.C 551 KB
Newer Older
hrchilds's avatar
hrchilds committed
1 2
/*****************************************************************************
*
3
* Copyright (c) 2000 - 2013, Lawrence Livermore National Security, LLC
hrchilds's avatar
hrchilds committed
4
* Produced at the Lawrence Livermore National Laboratory
5
* LLNL-CODE-442911
hrchilds's avatar
hrchilds committed
6 7
* All rights reserved.
*
8
* This file is  part of VisIt. For  details, see https://visit.llnl.gov/.  The
hrchilds's avatar
hrchilds committed
9 10 11 12 13 14 15 16 17 18
* full copyright notice is contained in the file COPYRIGHT located at the root
* of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html.
*
* Redistribution  and  use  in  source  and  binary  forms,  with  or  without
* modification, are permitted provided that the following conditions are met:
*
*  - Redistributions of  source code must  retain the above  copyright notice,
*    this list of conditions and the disclaimer below.
*  - Redistributions in binary form must reproduce the above copyright notice,
*    this  list of  conditions  and  the  disclaimer (as noted below)  in  the
19 20 21
*    documentation and/or other materials provided with the distribution.
*  - Neither the name of  the LLNS/LLNL nor the names of  its contributors may
*    be used to endorse or promote products derived from this software without
22
*    specific prior written permission
hrchilds's avatar
hrchilds committed
23 24 25 26
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT  HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR  IMPLIED WARRANTIES, INCLUDING,  BUT NOT  LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND  FITNESS FOR A PARTICULAR  PURPOSE
27 28 29
* ARE  DISCLAIMED. IN  NO EVENT  SHALL LAWRENCE  LIVERMORE NATIONAL  SECURITY,
* LLC, THE  U.S.  DEPARTMENT OF  ENERGY  OR  CONTRIBUTORS BE  LIABLE  FOR  ANY
* DIRECT,  INDIRECT,   INCIDENTAL,   SPECIAL,   EXEMPLARY,  OR   CONSEQUENTIAL
hrchilds's avatar
hrchilds committed
30 31 32 33 34 35 36 37 38
* DAMAGES (INCLUDING, BUT NOT  LIMITED TO, PROCUREMENT OF  SUBSTITUTE GOODS OR
* SERVICES; LOSS OF  USE, DATA, OR PROFITS; OR  BUSINESS INTERRUPTION) HOWEVER
* CAUSED  AND  ON  ANY  THEORY  OF  LIABILITY,  WHETHER  IN  CONTRACT,  STRICT
* LIABILITY, OR TORT  (INCLUDING NEGLIGENCE OR OTHERWISE)  ARISING IN ANY  WAY
* OUT OF THE  USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
*****************************************************************************/

hrchilds's avatar
hrchilds committed
39 40
#include <Python.h>
#include <stdio.h>
41
#include <visit-config.h> // for VISIT_VERSION
hrchilds's avatar
hrchilds committed
42 43
#if !defined(_WIN32)
#include <strings.h>
hrchilds's avatar
hrchilds committed
44 45
#else
#include <process.h> // for _getpid
hrchilds's avatar
hrchilds committed
46 47
#endif
#include <snprintf.h>
hrchilds's avatar
hrchilds committed
48
#include <map>
49 50
#include <string>
#include <vector>
hrchilds's avatar
hrchilds committed
51 52 53 54 55 56 57 58 59 60 61 62 63 64

#define THREADS

//
// Include threads
//
#ifdef THREADS
#if defined(_WIN32)
#include <windows.h>
#else
#include <pthread.h>
#endif
#endif

hrchilds's avatar
hrchilds committed
65
#include <visitmodulehelpers.h>
hrchilds's avatar
hrchilds committed
66
#include <Connection.h>
hrchilds's avatar
hrchilds committed
67 68 69
#include <Observer.h>
#include <ObserverToCallback.h>
#include <ViewerProxy.h>
hrchilds's avatar
hrchilds committed
70
#include <ViewerRPC.h>
hrchilds's avatar
hrchilds committed
71 72 73 74 75 76
#include <VisItException.h>
#include <LostConnectionException.h>
#include <PlotPluginInfo.h>
#include <PlotPluginManager.h>
#include <OperatorPluginInfo.h>
#include <OperatorPluginManager.h>
hrchilds's avatar
hrchilds committed
77
#include <QueryList.h>
78
#include <VisItInit.h>
hrchilds's avatar
hrchilds committed
79
#include <DebugStream.h>
80
#include <StringHelpers.h>
hrchilds's avatar
hrchilds committed
81
#include <Logging.h>
82
#include <SingleAttributeConfigManager.h>
83
#include <InstallationFunctions.h>
hrchilds's avatar
hrchilds committed
84 85 86 87 88 89

//
// State object include files.
//
#include <AnimationAttributes.h>
#include <AnnotationAttributes.h>
hrchilds's avatar
hrchilds committed
90 91
#include <AnnotationObject.h>
#include <AnnotationObjectList.h>
hrchilds's avatar
hrchilds committed
92 93 94
#include <ClientMethod.h>
#include <ClientInformation.h>
#include <ClientInformationList.h>
hrchilds's avatar
hrchilds committed
95
#include <ColorTableAttributes.h>
96
#include <ConstructDataBinningAttributes.h>
hrchilds's avatar
hrchilds committed
97 98
#include <DatabaseCorrelationList.h>
#include <DatabaseCorrelation.h>
hrchilds's avatar
hrchilds committed
99
#include <DBPluginInfoAttributes.h>
hrchilds's avatar
hrchilds committed
100
#include <EngineList.h>
hrchilds's avatar
hrchilds committed
101
#include <ExportDBAttributes.h>
102
#include <FileOpenOptions.h>
hrchilds's avatar
hrchilds committed
103
#include <GlobalAttributes.h>
hrchilds's avatar
hrchilds committed
104
#include <GlobalLineoutAttributes.h>
105
#include <HostProfileList.h>
hrchilds's avatar
hrchilds committed
106
#include <InteractorAttributes.h>
hrchilds's avatar
hrchilds committed
107
#include <KeyframeAttributes.h>
hrchilds's avatar
hrchilds committed
108
#include <MeshManagementAttributes.h>
hrchilds's avatar
hrchilds committed
109
#include <MessageAttributes.h>
hrchilds's avatar
hrchilds committed
110
#include <PickAttributes.h>
hrchilds's avatar
hrchilds committed
111
#include <Plot.h>
hrchilds's avatar
hrchilds committed
112
#include <PlotInfoAttributes.h>
hrchilds's avatar
hrchilds committed
113 114
#include <PlotList.h>
#include <PluginManagerAttributes.h>
hrchilds's avatar
hrchilds committed
115
#include <ProcessAttributes.h>
hrchilds's avatar
hrchilds committed
116
#include <QueryAttributes.h>
hrchilds's avatar
hrchilds committed
117 118
#include <PrinterAttributes.h>
#include <RenderingAttributes.h>
119 120
#include <SelectionProperties.h>
#include <SelectionList.h>
hrchilds's avatar
hrchilds committed
121 122
#include <StatusAttributes.h>
#include <SyncAttributes.h>
hrchilds's avatar
hrchilds committed
123
#include <QueryOverTimeAttributes.h>
hrchilds's avatar
hrchilds committed
124
#include <ViewAttributes.h>
125
#include <ViewAxisArrayAttributes.h>
hrchilds's avatar
hrchilds committed
126 127 128
#include <ViewCurveAttributes.h>
#include <View2DAttributes.h>
#include <View3DAttributes.h>
hrchilds's avatar
hrchilds committed
129 130 131
#include <WindowInformation.h>
#include <ExpressionList.h>
#include <Expression.h>
hrchilds's avatar
hrchilds committed
132
#include <LightList.h>
hrchilds's avatar
hrchilds committed
133 134 135 136

//
// Extension include files.
//
137
#include <PyAnimationAttributes.h>
hrchilds's avatar
hrchilds committed
138
#include <PyAnnotationAttributes.h>
whitlocb's avatar
whitlocb committed
139 140 141 142 143 144
#include <PyAxes2D.h>
#include <PyAxes3D.h>
#include <PyAxisAttributes.h>
#include <PyAxisLabels.h>
#include <PyAxisTickMarks.h>
#include <PyAxisTitles.h>
hrchilds's avatar
hrchilds committed
145 146 147 148
#include <PyColorAttribute.h>
#include <PyColorAttributeList.h>
#include <PyColorControlPoint.h>
#include <PyColorControlPointList.h>
149
#include <PyConstructDataBinningAttributes.h>
hrchilds's avatar
hrchilds committed
150
#include <PyDatabaseCorrelation.h>
whitlocb's avatar
whitlocb committed
151
#include <PyExportDBAttributes.h>
152 153
#include <PyExpression.h>
#include <PyExpressionList.h>
154
#include <PyFileOpenOptions.h>
whitlocb's avatar
whitlocb committed
155
#include <PyFontAttributes.h>
hrchilds's avatar
hrchilds committed
156 157
#include <PyGaussianControlPoint.h>
#include <PyGaussianControlPointList.h>
hrchilds's avatar
hrchilds committed
158
#include <PyGlobalAttributes.h>
hrchilds's avatar
hrchilds committed
159
#include <PyGlobalLineoutAttributes.h>
hrchilds's avatar
hrchilds committed
160
#include <PyImageObject.h>
hrchilds's avatar
hrchilds committed
161
#include <PyInteractorAttributes.h>
hrchilds's avatar
hrchilds committed
162
#include <PyKeyframeAttributes.h>
hrchilds's avatar
hrchilds committed
163
#include <PyLegendAttributesObject.h>
164
#include <PyLaunchProfile.h>
hrchilds's avatar
hrchilds committed
165
#include <PyLineObject.h>
hrchilds's avatar
hrchilds committed
166
#include <PyLightAttributes.h>
167
#include <PyMachineProfile.h>
hrchilds's avatar
hrchilds committed
168
#include <PyMaterialAttributes.h>
hrchilds's avatar
hrchilds committed
169
#include <PyMeshManagementAttributes.h>
hrchilds's avatar
hrchilds committed
170
#include <PyPickAttributes.h>
hrchilds's avatar
hrchilds committed
171
#include <PyPlotList.h>
hrchilds's avatar
hrchilds committed
172
#include <PyPrinterAttributes.h>
hrchilds's avatar
hrchilds committed
173
#include <PyProcessAttributes.h>
hrchilds's avatar
hrchilds committed
174 175
#include <PyRenderingAttributes.h>
#include <PySaveWindowAttributes.h>
176 177 178
#include <PySelectionProperties.h>
#include <PySelectionSummary.h>
#include <PySelectionList.h>
179
#include <PySILRestrictionBase.h>
hrchilds's avatar
hrchilds committed
180
#include <PySILRestriction.h>
hrchilds's avatar
hrchilds committed
181
#include <PyText2DObject.h>
whitlocb's avatar
whitlocb committed
182
#include <PyText3DObject.h>
hrchilds's avatar
hrchilds committed
183
#include <PyQueryOverTimeAttributes.h>
hrchilds's avatar
hrchilds committed
184
#include <PyTimeSliderObject.h>
hrchilds's avatar
hrchilds committed
185
#include <PyViewAttributes.h>
186
#include <PyViewAxisArrayAttributes.h>
hrchilds's avatar
hrchilds committed
187 188 189
#include <PyViewCurveAttributes.h>
#include <PyView2DAttributes.h>
#include <PyView3DAttributes.h>
hrchilds's avatar
hrchilds committed
190
#include <PyWindowInformation.h>
hrchilds's avatar
hrchilds committed
191
#include <PyavtDatabaseMetaData.h>
192
#include <PyViewerRPC.h>
hrchilds's avatar
hrchilds committed
193

cyrush's avatar
cyrush committed
194

195 196 197 198
// Variant & MapNode Helpers:
#include <PyVariant.h>
#include <PyMapNode.h>

199 200 201
#include <CallbackManager.h>
#include <ViewerRPCCallbacks.h>
#include <CallbackHandlers.h>
hrchilds's avatar
hrchilds committed
202
#include <MethodDoc.h>
hrchilds's avatar
hrchilds committed
203

hrchilds's avatar
hrchilds committed
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
#include <avtSILRestrictionTraverser.h>

//
// Defines.
//
#define STATIC

#define ADD_EXTENSION(GM) methods = GM(&nMethods); \
    for(i = 0; i < nMethods; ++i) \
    { \
        debug1 << "Added method: " << methods[i].ml_name << endl; \
        AddMethod(methods[i].ml_name, methods[i].ml_meth); \
    }

#define ENSURE_VIEWER_EXISTS() if(noViewer) {\
    PyErr_SetString(VisItError, "VisIt's viewer is not running!"); \
    return NULL; }

hrchilds's avatar
hrchilds committed
222 223
#define NO_ARGUMENTS() if(!PyArg_ParseTuple(args, "")) return NULL;

224
#if defined(_WIN32)
225 226 227
# if defined(visitmodule_EXPORTS)
#  define VISITMODULE_API __declspec(dllexport)
# else
228
#  define VISITMODULE_API 
229
# endif
230 231 232 233 234 235 236 237
#else
# if __GNUC__ >= 4
#   define VISITMODULE_API __attribute__ ((visibility("default")))
# else
#   define VISITMODULE_API /* not affected */
# endif
#endif

hrchilds's avatar
hrchilds committed
238 239 240 241 242
//
// Make the initvisit function callable from C.
//
extern "C"
{
243 244 245
    VISITMODULE_API void initvisit();
    VISITMODULE_API void cli_initvisit(int, bool, int, char **, int, char **);
    VISITMODULE_API void cli_runscript(const char *);
hrchilds's avatar
hrchilds committed
246 247 248

    // Expose these functions so we can call them from a facade
    // VisIt module from "import visit" inside of Python.
249 250 251
    VISITMODULE_API PyObject *visit_Launch(PyObject *, PyObject *);
    VISITMODULE_API PyObject *visit_SetDebugLevel(PyObject *, PyObject *);
    VISITMODULE_API PyObject *visit_AddArgument(PyObject *, PyObject *);
hrchilds's avatar
hrchilds committed
252 253 254 255 256 257 258 259 260 261 262 263 264
}

//
// Prototypes
//
static void terminatevisit();
#if defined(_WIN32)
static DWORD WINAPI visit_eventloop(LPVOID);
#else
static void *visit_eventloop(void *);
#endif
static void CloseModule();
static void CreateListenerThread();
hrchilds's avatar
hrchilds committed
265
static void LaunchViewer(const char *);
hrchilds's avatar
hrchilds committed
266 267 268 269 270
static int  Synchronize();
static void DelayedLoadPlugins();
static void PlotPluginAddInterface();
static void OperatorPluginAddInterface();
static void InitializeExtensions();
hrchilds's avatar
hrchilds committed
271
static void ExecuteClientMethod(ClientMethod *method, bool onNewThread);
272
static int InitializeViewerProxy(ViewerProxy* viewerproxy = NULL);
hrchilds's avatar
hrchilds committed
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
//
// Type definitions
//

struct AttributesObject
{
    PyObject_HEAD
    AttributeSubject *data;
};

//
// This is an observer that watches the viewer's message attributes and
// prints an error message when a message comes in.
//
// Modifications:
//   Brad Whitlock, Fri Jul 26 11:47:40 PDT 2002
//   I made this class have methods to return information about the last
//   error that came in.
//
292 293 294 295
//   Mark C. Miller, Tue Nov 27 10:44:29 PST 2007
//   Added suppression level; 4 means nothing is suppressed; 1 means
//   everything is suppressed.
//
whitlocb's avatar
whitlocb committed
296 297 298
//   Brad Whitlock, Fri Jan 18 15:00:41 PST 2008
//   Added Information printing.
//
hrchilds's avatar
hrchilds committed
299 300 301 302 303 304
class VisItMessageObserver : public Observer
{
public:
    VisItMessageObserver(Subject *s) : Observer(s), lastError("")
    {
        errorFlag = 0;
whitlocb's avatar
whitlocb committed
305
        suppressLevel = 4;
hrchilds's avatar
hrchilds committed
306 307 308 309 310 311 312 313
    };

    virtual ~VisItMessageObserver() { };

    void ClearError()
    {
        errorFlag = 0;
    };
314 315 316
    int SetSuppressLevel(int newLevel)
    {
        int oldLevel = suppressLevel;
whitlocb's avatar
whitlocb committed
317 318
        suppressLevel = newLevel;
        return oldLevel;
319
    };
hrchilds's avatar
hrchilds committed
320

321
    int GetSuppressLevel() const { return suppressLevel; };
hrchilds's avatar
hrchilds committed
322 323 324 325 326 327 328 329 330 331 332 333 334
    int ErrorFlag() const { return errorFlag; };
    const std::string &GetLastError() const { return lastError; };

    virtual void Update(Subject *s)
    {
        MessageAttributes *m = (MessageAttributes *)s;

        if(m->GetSeverity() == MessageAttributes::Error)
        {
            // Store information about the error.
            errorFlag = 1;
            lastError = m->GetText();

whitlocb's avatar
whitlocb committed
335
            if (suppressLevel > 1)
336
                fprintf(stderr, "VisIt: Error - %s\n", m->GetText().c_str());
hrchilds's avatar
hrchilds committed
337 338 339 340
//            // This can't really be done this way since this code is only
//            // ever called by the 2nd thread. It cannot use Python.
//            VisItErrorFunc(m->GetText().c_str());
        }
hrchilds's avatar
hrchilds committed
341 342
        else if(m->GetSeverity() == MessageAttributes::ErrorClear)
            errorFlag = 0;
343
        else if(m->GetSeverity() == MessageAttributes::Warning &&
344
            suppressLevel > 2)
hrchilds's avatar
hrchilds committed
345
            fprintf(stderr, "VisIt: Warning - %s\n", m->GetText().c_str());
346
        else if (suppressLevel > 3)
whitlocb's avatar
whitlocb committed
347 348 349 350 351 352
        {
            if(m->GetSeverity() == MessageAttributes::Message)
                fprintf(stderr, "VisIt: Message - %s\n", m->GetText().c_str());
            else
                fprintf(stderr, "VisIt: Information - %s\n", m->GetText().c_str());
        }
hrchilds's avatar
hrchilds committed
353 354 355
    }
private:
    int         errorFlag;
356
    int         suppressLevel;
hrchilds's avatar
hrchilds committed
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
    std::string lastError;
};

//
// This is an observer that watches the viewer's status attributes and
// prints out status messages that come in.
//
class VisItStatusObserver : public Observer
{
public:
    VisItStatusObserver(Subject *s) : Observer(s)
    {
        verbose = false;
    };

    virtual ~VisItStatusObserver() { };

    void SetVerbose(bool val) { verbose = val; };

    virtual void Update(Subject *s)
    {
        StatusAttributes *statusAtts = (StatusAttributes *)s;

        // Update the status bar.
        if(verbose && !statusAtts->GetClearStatus())
        {
            // If the message field is selected, use it. Otherwise, make up
            // a message based on the other fields.
            if(statusAtts->GetMessageType() == 1)
hrchilds's avatar
hrchilds committed
386
                fprintf(stderr, "%s\n", statusAtts->GetStatusMessage().c_str());
hrchilds's avatar
hrchilds committed
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
            else if (statusAtts->GetMessageType() == 2)
            {
                int total;
                if (statusAtts->GetMaxStage() > 0)
                {
                    float pct0  = float(statusAtts->GetPercent()) / 100.;
                    float pct1  = float(statusAtts->GetCurrentStage()-1) / float(statusAtts->GetMaxStage());
                    float pct2  = float(statusAtts->GetCurrentStage())   / float(statusAtts->GetMaxStage());
                    total = int(100. * ((pct0 * pct2) + ((1.-pct0) * pct1)));
                }
                else
                    total = 0;

                fprintf(stderr, "%d%% done: %s (%d%% of stage %d/%d)\n",
                    total,
                    statusAtts->GetCurrentStageName().c_str(),
                    statusAtts->GetPercent(),
                    statusAtts->GetCurrentStage(),
                    statusAtts->GetMaxStage());
            }
cyrush's avatar
cyrush committed
407
        }
hrchilds's avatar
hrchilds committed
408 409 410 411 412 413 414 415
    }
private:
    bool verbose;
};

//
// VisIt module state flags and objects.
//
hrchilds's avatar
hrchilds committed
416
ViewerProxy                 *viewer = 0;
417
std::vector<std::string>     viewerArguments;
418
bool                         localNameSpace = false;
hrchilds's avatar
hrchilds committed
419

hrchilds's avatar
hrchilds committed
420 421 422
static PyObject             *visitModule = 0;
static bool                  moduleInitialized = false;
static bool                  keepGoing = true;
423
static bool                  autoUpdate = false;
hrchilds's avatar
hrchilds committed
424
static bool                  viewerInitiatedQuit = false;
hrchilds's avatar
hrchilds committed
425
static bool                  viewerBlockingRead = false;
426
static bool                  viewerEmbedded = false;
hrchilds's avatar
hrchilds committed
427 428 429 430 431 432 433
#ifdef THREADS
static bool                  moduleUseThreads = true;
#else
static bool                  moduleUseThreads = false;
#endif
static bool                  noViewer = true;
static int                   moduleDebugLevel = 0;
434
static bool                  moduleBufferDebug = false;
hrchilds's avatar
hrchilds committed
435 436 437 438
static VisItMessageObserver *messageObserver = 0;
static VisItStatusObserver  *statusObserver = 0;
static bool                  moduleVerbose = false;
static ObserverToCallback   *pluginLoader = 0;
hrchilds's avatar
hrchilds committed
439
static ObserverToCallback   *clientMethodObserver = 0;
hrchilds's avatar
hrchilds committed
440
static ObserverToCallback   *stateLoggingObserver = 0;
hrchilds's avatar
hrchilds committed
441 442
static bool                  interruptScript = false;
static int                   syncCount = 1000;
hrchilds's avatar
hrchilds committed
443
static PyObject             *VisItError;
hrchilds's avatar
hrchilds committed
444
static PyObject             *VisItInterrupt;
hrchilds's avatar
hrchilds committed
445 446 447

static int                   cli_argc = 0;
static char                **cli_argv = 0;
whitlocb's avatar
whitlocb committed
448 449
static int                   cli_argc_after_s = 0;
static char                **cli_argv_after_s = 0;
hrchilds's avatar
hrchilds committed
450

hrchilds's avatar
hrchilds committed
451 452
static PyThreadState        *mainThreadState = NULL;

hrchilds's avatar
hrchilds committed
453 454
static bool                  clientMethodsAllowed = false;
static std::vector<ClientMethod *> cachedClientMethods;
hrchilds's avatar
hrchilds committed
455

whitlocb's avatar
whitlocb committed
456 457
static std::map<std::string, PyObject*> macroFunctions;

458 459
static CallbackManager      *callbackMgr = NULL;
static ViewerRPCCallbacks   *rpcCallbacks = NULL;
hrchilds's avatar
hrchilds committed
460

461
static std::string ultraScriptFile = "";
hrchilds's avatar
hrchilds committed
462 463 464 465 466 467 468 469
typedef struct
{
    AnnotationObject *object;
    int               index;
    int               refCount;
} AnnotationObjectRef;

static std::map<std::string, AnnotationObjectRef> localObjectMap;
hrchilds's avatar
hrchilds committed
470

471
static bool                  suppressQueryOutputState = false;
472 473 474 475 476
// pickle related
bool      pickleReady=false;
PyObject *pickleDumps=NULL;
PyObject *pickleLoads=NULL;

hrchilds's avatar
hrchilds committed
477 478
#ifdef THREADS
#if defined(_WIN32)
hrchilds's avatar
hrchilds committed
479 480 481 482 483
static CRITICAL_SECTION      mutex;
static HANDLE                threadHandle = INVALID_HANDLE_VALUE;
static bool                  waitingForViewer = false;
static ObserverToCallback   *synchronizeCallback = 0;
static HANDLE                received_sync_from_viewer = INVALID_HANDLE_VALUE;
hrchilds's avatar
hrchilds committed
484 485
#define THREAD_INIT()
#define MUTEX_CREATE()       InitializeCriticalSection(&mutex)
cyrush's avatar
cyrush committed
486
#define MUTEX_DESTROY()
hrchilds's avatar
hrchilds committed
487 488
#define MUTEX_LOCK()         EnterCriticalSection(&mutex)
#define MUTEX_UNLOCK()       LeaveCriticalSection(&mutex)
hrchilds's avatar
hrchilds committed
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507

#define SYNC_COND_WAIT()     MUTEX_UNLOCK(); \
                             if(keepGoing) \
                             {\
                                 waitingForViewer = true; \
                                 WaitForSingleObject(received_sync_from_viewer, INFINITE); \
                                 waitingForViewer = false; \
                             }

#define SYNC_WAKE_MAIN_THREAD() if(waitingForViewer) \
                                    WakeMainThread(0, 0);

#define SYNC_CREATE()        received_sync_from_viewer = CreateEvent(NULL, FALSE, FALSE, NULL);

#define SYNC_DESTROY()       CloseHandle(received_sync_from_viewer);

// ****************************************************************************
// Function: WakeMainThread
//
cyrush's avatar
cyrush committed
508
// Purpose:
hrchilds's avatar
hrchilds committed
509 510 511 512 513 514 515 516 517 518 519
//   Called by the listener thread when SyncAttributes is read from the viewer.
//
// Programmer: Brad Whitlock
// Creation:   Mon Mar 20 12:00:06 PST 2006
//
// Modifications:
//
// ****************************************************************************

static void WakeMainThread(Subject *, void *)
{
hrchilds's avatar
hrchilds committed
520
    if(GetViewerState()->GetSyncAttributes()->GetSyncTag() == syncCount || !keepGoing)
hrchilds's avatar
hrchilds committed
521 522 523
        SetEvent(received_sync_from_viewer);
}

hrchilds's avatar
hrchilds committed
524 525 526
#else
// pthreads thread-related stuff.
static pthread_attr_t        thread_atts;
hrchilds's avatar
hrchilds committed
527
static pthread_mutex_t       mutex;
hrchilds's avatar
hrchilds committed
528 529 530
static pthread_cond_t        received_sync_from_viewer;
static bool waitingForViewer = false;
static ObserverToCallback   *synchronizeCallback = 0;
531
#define THREAD_INIT()        pthread_attr_init(&thread_atts)
hrchilds's avatar
hrchilds committed
532 533 534 535
#define MUTEX_CREATE()       pthread_mutex_init(&mutex, NULL)
#define MUTEX_DESTROY()      pthread_mutex_destroy(&mutex)
#define MUTEX_LOCK()         pthread_mutex_lock(&mutex)
#define MUTEX_UNLOCK()       pthread_mutex_unlock(&mutex)
hrchilds's avatar
hrchilds committed
536 537 538 539 540

#define SYNC_COND_WAIT()     if(keepGoing) \
                             {\
                                 waitingForViewer = true; \
                                 pthread_cond_wait(&received_sync_from_viewer, \
hrchilds's avatar
hrchilds committed
541
                                                   &mutex); \
hrchilds's avatar
hrchilds committed
542
                                 waitingForViewer = false; \
hrchilds's avatar
hrchilds committed
543 544
                             }\
                             MUTEX_UNLOCK();
hrchilds's avatar
hrchilds committed
545

hrchilds's avatar
hrchilds committed
546 547
#define SYNC_WAKE_MAIN_THREAD() if(waitingForViewer) \
                                    WakeMainThread(0, 0);
hrchilds's avatar
hrchilds committed
548 549 550
#define SYNC_CREATE()        pthread_cond_init(&received_sync_from_viewer, NULL);

#define SYNC_DESTROY()       pthread_cond_destroy(&received_sync_from_viewer);
hrchilds's avatar
hrchilds committed
551 552


hrchilds's avatar
hrchilds committed
553 554 555
// ****************************************************************************
// Function: WakeMainThread
//
cyrush's avatar
cyrush committed
556
// Purpose:
hrchilds's avatar
hrchilds committed
557 558 559 560 561 562 563 564 565 566 567 568
//   Called by the listener thread when SyncAttributes is read from the viewer.
//
// Programmer: Brad Whitlock
// Creation:   Mon Jun 27 09:58:06 PDT 2005
//
// Modifications:
//   Brad Whitlock, Mon Jun 27 10:01:06 PDT 2005
//   I removed the secondary mutexes since this method gets called only from
//   the listener thread, which has already locked the viewer mutex.
//
// ****************************************************************************

hrchilds's avatar
hrchilds committed
569
static void WakeMainThread(Subject *, void *)
hrchilds's avatar
hrchilds committed
570
{
hrchilds's avatar
hrchilds committed
571
    if(GetViewerState()->GetSyncAttributes()->GetSyncTag() == syncCount || !keepGoing)
hrchilds's avatar
hrchilds committed
572 573 574
        pthread_cond_signal(&received_sync_from_viewer);
}

hrchilds's avatar
hrchilds committed
575 576
#endif
#else
hrchilds's avatar
hrchilds committed
577
#define POLLING_SYNCHRONIZE
hrchilds's avatar
hrchilds committed
578 579 580 581
#define MUTEX_CREATE()
#define MUTEX_DESTROY()
#define MUTEX_LOCK()
#define MUTEX_UNLOCK()
hrchilds's avatar
hrchilds committed
582
#define THREAD_INIT()
hrchilds's avatar
hrchilds committed
583 584
#endif

585 586 587 588 589 590
// Locks the Python interpreter by one thread.
PyThreadState *
VisItLockPythonInterpreter()
{
    // get the global lock
    PyEval_AcquireLock();
hrchilds's avatar
hrchilds committed
591

592 593 594 595 596 597 598 599
    // get a reference to the PyInterpreterState
    PyInterpreterState * mainInterpreterState = mainThreadState->interp;
    // create a thread state object for this thread
    PyThreadState *myThreadState = PyThreadState_New(mainInterpreterState);
    // swap in my thread state
    PyThreadState_Swap(myThreadState);
    return myThreadState;
}
hrchilds's avatar
hrchilds committed
600

601 602 603 604 605 606 607 608 609 610 611 612 613
// Unlocks the Python interpreter by one thread.
void
VisItUnlockPythonInterpreter(PyThreadState *myThreadState)
{
    // clear the thread state
    PyThreadState_Swap(NULL);
    // clear out any cruft from thread state object
    PyThreadState_Clear(myThreadState);
    // delete my thread state object
    PyThreadState_Delete(myThreadState);
    // release our hold on the global interpreter
    PyEval_ReleaseLock();
}
hrchilds's avatar
hrchilds committed
614

hrchilds's avatar
hrchilds committed
615 616 617
// ****************************************************************************
// Function: IntReturnValue
//
cyrush's avatar
cyrush committed
618
// Purpose:
hrchilds's avatar
hrchilds committed
619
//   Returns a Python long, which indicates the success value for the VisIt
cyrush's avatar
cyrush committed
620
//   methods. If errorFlag < 0 then the viewer died. Return 0 so the
hrchilds's avatar
hrchilds committed
621 622 623 624 625 626 627 628 629 630
//   interpreter stops.
//
// Arguments:
//   errorFlag : The error Flag. 0 means success. 1 means failure. -1 means
//               that the viewer died.
//
// Programmer: Brad Whitlock
// Creation:   Fri Dec 19 12:31:01 PDT 2003
//
// Modifications:
cyrush's avatar
cyrush committed
631
//
hrchilds's avatar
hrchilds committed
632 633 634 635 636 637 638 639 640 641 642 643 644
// ****************************************************************************

PyObject *
IntReturnValue(int errorFlag)
{
    PyObject *retval = NULL;

    if(errorFlag >= 0)
        retval = PyLong_FromLong(long(errorFlag == 0));

    return retval;
}

hrchilds's avatar
hrchilds committed
645 646 647
// ****************************************************************************
// Function: DeprecatedMessage
//
cyrush's avatar
cyrush committed
648
// Purpose:
hrchilds's avatar
hrchilds committed
649 650 651 652 653 654 655 656 657 658 659
//   Prints a message for a deprecated function.
//
// Arguments:
//   deprecatedFunction : The function that was deprecated.
//   var                : The version in which the function was deprecated.
//   newFunction        : The new function that should be called.
//
// Programmer: Brad Whitlock
// Creation:   Tue Mar 2 08:58:03 PDT 2004
//
// Modifications:
cyrush's avatar
cyrush committed
660
//
hrchilds's avatar
hrchilds committed
661 662 663 664 665 666
// ****************************************************************************

void
DeprecatedMessage(const char *deprecatedFunction, const char *ver,
    const char *newFunction)
{
cyrush's avatar
cyrush committed
667
    fprintf(stderr,
hrchilds's avatar
hrchilds committed
668 669 670 671 672 673 674 675
            "***\n"
            "*** %s was deprecated in version %s.\n"
            "*** Calling %s will still work for now but you should\n"
            "*** update your code so it uses the %s function.\n"
            "***\n",
            deprecatedFunction, ver, deprecatedFunction, newFunction);
}

hrchilds's avatar
hrchilds committed
676 677 678
// ****************************************************************************
// Method: StringVectorToTupleString
//
cyrush's avatar
cyrush committed
679
// Purpose:
hrchilds's avatar
hrchilds committed
680 681 682 683 684 685 686 687
//   Converts a stringVector into a suitable string representation of a Python
//   tuple.
//
// Arguments:
//   s : The string vector.
//
// Returns:    A string representation of the string tuple.
//
cyrush's avatar
cyrush committed
688
// Note:
hrchilds's avatar
hrchilds committed
689 690 691 692 693
//
// Programmer: Brad Whitlock
// Creation:   Tue Jan 10 14:02:23 PST 2006
//
// Modifications:
cyrush's avatar
cyrush committed
694
//
hrchilds's avatar
hrchilds committed
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
// ****************************************************************************

static std::string
StringVectorToTupleString(const stringVector &s)
{
    std::string str;

    if(s.size() > 1)
        str += "(";
    for(int i = 0; i < s.size(); ++i)
    {
        str += "\"";
        str += s[i];
        str += "\"";
        if(i < s.size()-1)
            str += ", ";
    }
    if(s.size() > 1)
        str += "(";

    return str;
}

hrchilds's avatar
hrchilds committed
718 719 720
// ****************************************************************************
// Method: GetStringVectorFromPyObject
//
cyrush's avatar
cyrush committed
721
// Purpose:
hrchilds's avatar
hrchilds committed
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
//   Populates a string vector from values in a PyObject.
//
// Arguments:
//   obj : The PyObject that we're checking for strings.
//   vec : The string vector that we're populating.
//
// Returns:    True if successful; false otherwise.
//
// Note:       Adapted from ParseTupleForVars but it can parse more than
//             tuples.
//
// Programmer: Brad Whitlock
// Creation:   Tue Mar 2 09:51:39 PDT 2004
//
// Modifications:
cyrush's avatar
cyrush committed
737
//
hrchilds's avatar
hrchilds committed
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
// ****************************************************************************

bool
GetStringVectorFromPyObject(PyObject *obj, stringVector &vec)
{
    bool retval = true;

    if(obj == 0)
    {
        retval = false;
    }
    else if(PyTuple_Check(obj))
    {
        // Extract arguments from the tuple.
        for(int i = 0; i < PyTuple_Size(obj); ++i)
        {
            PyObject *item = PyTuple_GET_ITEM(obj, i);
            if(PyString_Check(item))
                vec.push_back(PyString_AS_STRING(item));
            else
            {
                VisItErrorFunc("The tuple must contain all strings.");
                retval = false;
                break;
            }
        }
    }
    else if(PyList_Check(obj))
    {
        // Extract arguments from the list.
        for(int i = 0; i < PyList_Size(obj); ++i)
        {
            PyObject *item = PyList_GET_ITEM(obj, i);
            if(PyString_Check(item))
                vec.push_back(PyString_AS_STRING(item));
            else
            {
                VisItErrorFunc("The list must contain all strings.");
                retval = false;
                break;
            }
        }
    }
    else if(PyString_Check(obj))
    {
        vec.push_back(PyString_AS_STRING(obj));
    }
    else
    {
        retval = false;
        VisItErrorFunc("The object could not be converted to a "
                       "vector of strings.");
    }

    return retval;
}

// ****************************************************************************
// Method: GetDoubleArrayFromPyObject
//
cyrush's avatar
cyrush committed
798
// Purpose:
hrchilds's avatar
hrchilds committed
799 800 801 802 803 804 805 806 807 808 809 810 811
//   Fills a double array with values from a tuple or list.
//
// Arguments:
//   obj    : The PyObject from which we're getting the values.
//   array  : The destination array.
//   maxLen : The length of the destination array.
//
// Returns:    True if successful; false otherwise.
//
// Programmer: Brad Whitlock
// Creation:   Tue Mar 2 10:14:33 PDT 2004
//
// Modifications:
cyrush's avatar
cyrush committed
812
//
hrchilds's avatar
hrchilds committed
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
// ****************************************************************************

bool
GetDoubleArrayFromPyObject(PyObject *obj, double *array, int maxLen)
{
    bool retval = true;

    if(obj == 0)
    {
        retval = false;
    }
    else if(PyTuple_Check(obj))
    {
        int size = PyTuple_Size(obj);
        for(int i = 0; i < size && i < maxLen; ++i)
        {
            PyObject *item = PyTuple_GET_ITEM(obj, i);
            if(PyFloat_Check(item))
                array[i] = PyFloat_AS_DOUBLE(item);
            else if(PyInt_Check(item))
                array[i] = double(PyInt_AS_LONG(item));
            else if(PyLong_Check(item))
                array[i] = double(PyLong_AsDouble(item));
        }
    }
    else if(PyList_Check(obj))
    {
        int size = PyList_Size(obj);
        for(int i = 0; i < size && i < maxLen; ++i)
        {
            PyObject *item = PyList_GET_ITEM(obj, i);
            if(PyFloat_Check(item))
                array[i] = PyFloat_AS_DOUBLE(item);
            else if(PyInt_Check(item))
                array[i] = double(PyInt_AS_LONG(item));
            else if(PyLong_Check(item))
                array[i] = double(PyLong_AsDouble(item));
        }
    }
    else if(PyFloat_Check(obj))
    {
        array[0] = PyFloat_AS_DOUBLE(obj);
    }
    else if(PyInt_Check(obj))
    {
        array[0] = double(PyInt_AS_LONG(obj));
    }
    else if(PyLong_Check(obj))
    {
        array[0] = double(PyLong_AsDouble(obj));
    }
    else
    {
        retval = false;
    }

    return retval;
}

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
// ****************************************************************************
//  Method:  PickleInit
//
//  Purpose:
//    Sets up pointer to pickle.dumps & pickle.loads methods.
//
//
//  Programmer:  Cyrus Harrison
//  Creation:    Fri Jul  9 14:27:52 PDT 2010
//
//  Modifications:
//
// ****************************************************************************
void PickleInit()
{
    if(!pickleReady)
    {
        PyObject *pickleModule = PyImport_ImportModule("pickle"); // new ref
        PyObject *pickleDict   = PyModule_GetDict(pickleModule);  // borrowed

        pickleDumps  = PyDict_GetItemString(pickleDict, "dumps"); // borrowed
        pickleLoads  = PyDict_GetItemString(pickleDict, "loads"); // borrowed
        Py_INCREF(pickleDumps);
        Py_INCREF(pickleLoads  );

        Py_DECREF(pickleModule);
        pickleReady = true;
    }
}
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916

// ****************************************************************************
//  Method:  FillDBOptionsFromDictionary
//
//  Purpose:
//    Take a dictionary of key-value pairs, ("boolval":1, "stringval":"foobar")
//    and applies it to a DBOptionsAttributes structure.  The error
//    reporting should hopefully be sufficient to guide users.
//
//  Arguments:
//    obj        the dictionary
//    opts       the DBOptionsAttributes to fill
//
//  Programmer:  Jeremy Meredith
//  Creation:    October 11, 2007
//
917 918 919 920
//  Modifications:
//    Jeremy Meredith, Thu Oct 25 10:05:37 EDT 2007
//    Added support for pre-2.5 versions of Python.
//
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
// ****************************************************************************
bool
FillDBOptionsFromDictionary(PyObject *obj, DBOptionsAttributes &opts)
{
    if (!obj)
        return false;

    char msg[256];
    bool isdict = PyDict_Check(obj);
    if (!isdict)
    {
        VisItErrorFunc("Expected a dictionary for DB Options");
        return false;
    }

    PyObject *key, *value;
937
#if PY_VERSION_HEX >= 0x02050000
938
    Py_ssize_t pos = 0;
939 940 941
#else
    int pos = 0;
#endif
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

    while (PyDict_Next(obj, &pos, &key, &value))
    {
        std::string name;
        if (PyString_Check(key))
            name = PyString_AS_STRING(key);
        else
        {
            VisItErrorFunc("The key for an option must be a string.");
            return false;
        }

        int index = -1;
        for (int j=0; j<opts.GetNumberOfOptions(); j++)
        {
            if (name == opts.GetName(j))
            {
                index = j;
                break;
            }
        }
        if (index == -1)
        {
            sprintf(msg, "There was no '%s' in the DB options.", name.c_str());
            VisItErrorFunc(msg);
            return false;
        }

        switch (opts.GetType(index))
        {
          case DBOptionsAttributes::Bool:
            if (PyInt_Check(value))
                opts.SetBool(name, PyInt_AS_LONG(value));
            else
            {
                sprintf(msg, "Expected int to set boolean '%s'", name.c_str());
                VisItErrorFunc(msg);
                return false;
            }
            break;
          case DBOptionsAttributes::Int:
            if (PyInt_Check(value))
                opts.SetInt(name, PyInt_AS_LONG(value));
            else
            {
                sprintf(msg, "Expected integer to set '%s'", name.c_str());
                VisItErrorFunc(msg);
                return false;
            }
            break;
          case DBOptionsAttributes::Float:
            if (PyFloat_Check(value))
                opts.SetFloat(name, PyFloat_AS_DOUBLE(value));
            else if (PyInt_Check(value))
                opts.SetFloat(name, PyInt_AS_LONG(value));
            else
            {
                sprintf(msg, "Expected float to set '%s'", name.c_str());
                VisItErrorFunc(msg);
                return false;
            }
            break;
          case DBOptionsAttributes::Double:
            if (PyFloat_Check(value))
                opts.SetDouble(name, PyFloat_AS_DOUBLE(value));
            else if (PyInt_Check(value))
                opts.SetDouble(name, PyInt_AS_LONG(value));
            else
            {
                sprintf(msg, "Expected float to set '%s'", name.c_str());
                VisItErrorFunc(msg);
                return false;
            }
            break;
          case DBOptionsAttributes::String:
            if (PyString_Check(value))
                opts.SetString(name, PyString_AS_STRING(value));
            else
            {
                sprintf(msg, "Expected string to set '%s'", name.c_str());
                VisItErrorFunc(msg);
                return false;
            }
            break;
          case DBOptionsAttributes::Enum:
            if (PyInt_Check(value))
                opts.SetEnum(name, PyInt_AS_LONG(value));
            else
            {
                sprintf(msg, "Expected int to set enum '%s'", name.c_str());
                VisItErrorFunc(msg);
                return false;
            }
            break;
        }
    }

    return true;
}

// ****************************************************************************
//  Method:  CreateDictionaryFromDBOptions
//
//  Purpose:
//    Create a dictionary of key-value pairs ("boolval":1,"stringval":"foobar")
//    from a DBOptionsAttributes structure.
//
//  Arguments:
//    opts       the DBOptionsAttributes to convert
//
//  Programmer:  Jeremy Meredith
//  Creation:    October 11, 2007
//
1055 1056 1057 1058
//  Modifications:
//    Jeremy Meredith, Thu Oct 25 10:05:37 EDT 2007
//    Added support for pre-2.5 versions of Python.
//
js9's avatar
js9 committed
1059 1060 1061
//    Jeremy Meredith, Tue Apr 29 15:18:13 EDT 2008
//    Fixing ABW bug.
//
1062 1063 1064 1065 1066 1067 1068
// ****************************************************************************
PyObject *
CreateDictionaryFromDBOptions(DBOptionsAttributes &opts)
{
    PyObject *dict = PyDict_New();
    for (int j=0; j<opts.GetNumberOfOptions(); j++)
    {
1069 1070
        // Older pythons don't support const char* in the PyDict routines,
        // so we have to copy this into a non-const string.
js9's avatar
js9 committed
1071
        char *name = new char[opts.GetName(j).length()+1];
1072
        strcpy(name, opts.GetName(j).c_str());
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
        switch (opts.GetType(j))
        {
          case DBOptionsAttributes::Bool:
            PyDict_SetItemString(dict,name,PyInt_FromLong(opts.GetBool(name)));
            break;
          case DBOptionsAttributes::Int:
            PyDict_SetItemString(dict,name,PyInt_FromLong(opts.GetInt(name)));
            break;
          case DBOptionsAttributes::Float:
            PyDict_SetItemString(dict,name,PyFloat_FromDouble(opts.GetFloat(name)));
            break;
          case DBOptionsAttributes::Double:
            PyDict_SetItemString(dict,name,PyFloat_FromDouble(opts.GetDouble(name)));
            break;
          case DBOptionsAttributes::String:
            PyDict_SetItemString(dict,name,PyString_FromString(opts.GetString(name).c_str()));
            break;
          case DBOptionsAttributes::Enum:
            PyDict_SetItemString(dict,name,PyInt_FromLong(opts.GetEnum(name)));
            break;
        }
1094
        delete[] name;
1095 1096 1097 1098 1099 1100
    }
    return dict;
}



hrchilds's avatar
hrchilds committed
1101 1102 1103 1104 1105 1106 1107
//
// Python callbacks for VisIt
//

// ****************************************************************************
// Function: visit_AddArgument
//
cyrush's avatar
cyrush committed
1108
// Purpose:
hrchilds's avatar
hrchilds committed
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
//   This is a Python callback that can be used to add arguments that are
//   passed to the viewer before it is created.
//
// Note:       Only has an effect before the viewer is created.
//
// Programmer: Brad Whitlock
// Creation:   Tue Sep 18 14:04:06 PST 2001
//
// Modifications:
//   Brad Whitlock, Mon Feb 4 16:55:58 PST 2002
//   Removed code to flag certain arguments.
//
// ****************************************************************************

hrchilds's avatar
hrchilds committed
1123
PyObject *
hrchilds's avatar
hrchilds committed
1124 1125 1126 1127 1128 1129 1130 1131
visit_AddArgument(PyObject *self, PyObject *args)
{
    if(noViewer)
    {
        char *arg;
        if(!PyArg_ParseTuple(args, "s", &arg))
            return NULL;

hkrishna's avatar
hkrishna committed
1132
        if(strcmp(arg,"-pyuiembedded") == 0)
1133 1134
            viewerEmbedded = true;

1135 1136
        //GetViewerProxy()->AddArgument(arg);
        viewerArguments.push_back(arg);
hrchilds's avatar
hrchilds committed
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
    }
    else
    {
        VisItErrorFunc("VisIt's viewer is already launched!");
        return NULL;
    }

    Py_INCREF(Py_None);
    return Py_None;
}

// ****************************************************************************
// Function: visit_Version
//
cyrush's avatar
cyrush committed
1151
// Purpose:
hrchilds's avatar
hrchilds committed
1152 1153 1154 1155 1156 1157 1158 1159
//   This is a Python callback that returns the Version of the VisIt module.
//
// Note:       Can be called before the viewer is created.
//
// Programmer: Brad Whitlock
// Creation:   Tue Sep 18 14:04:06 PST 2001
//
// Modifications:
cyrush's avatar
cyrush committed
1160
//
hrchilds's avatar
hrchilds committed
1161 1162 1163 1164 1165
// ****************************************************************************

STATIC PyObject *
visit_Version(PyObject *self, PyObject *args)
{
hrchilds's avatar
hrchilds committed
1166
    NO_ARGUMENTS();
1167
    return PyString_FromString(VISIT_VERSION);
hrchilds's avatar
hrchilds committed
1168 1169 1170 1171 1172
}

// ****************************************************************************
// Function: visit_Launch
//
cyrush's avatar
cyrush committed
1173
// Purpose:
hrchilds's avatar
hrchilds committed
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
//   This is a Python callback that launches the viewer.
//
// Note:       Only has an effect before the viewer is created.
//
// Programmer: Brad Whitlock
// Creation:   Tue Sep 18 14:04:06 PST 2001
//
// Modifications:
//   Brad Whitlock, Mon May 6 14:01:17 PST 2002
//   I moved the function calls that add the plugin interfaces to after the
//   call to Synchronize. This ensures that all state objects have good
//   default values from the viewer before we initialize local default values.
//
hrchilds's avatar
hrchilds committed
1187 1188 1189 1190 1191
//   Brad Whitlock, Mon Jun 27 09:31:24 PDT 2005
//   Added code to handle client events that come up during launch after the
//   launch has happened. This prevents client methods from stalling the
//   launch process.
//
hrchilds's avatar
hrchilds committed
1192 1193 1194
//   Brad Whitlock, Wed Nov 22 14:31:34 PST 2006
//   I added code to accept the name of the VisIt script to run.
//
1195 1196 1197
//   Jeremy Meredith, Thu Aug  7 15:06:45 EDT 2008
//   Change string literals to const char*'s.
//
hrchilds's avatar
hrchilds committed
1198 1199
// ****************************************************************************

hrchilds's avatar
hrchilds committed
1200
PyObject *
hrchilds's avatar
hrchilds committed
1201 1202
visit_Launch(PyObject *self, PyObject *args)
{
hrchilds's avatar
hrchilds committed
1203 1204
    debug1 << "Launch: 0" << endl;

hrchilds's avatar
hrchilds committed
1205 1206 1207 1208 1209 1210 1211 1212 1213
    //
    // Check to see if the viewer is already launched.
    //
    if(!noViewer)
    {
        VisItErrorFunc("VisIt's viewer is already launched!");
        return NULL;
    }

hrchilds's avatar
hrchilds committed
1214 1215 1216
    //
    // Determine if the function was called with any arguments.
    //
1217 1218
    const char *visitProgram = 0;
    static const char *visitProgramDefault = "visit";
hrchilds's avatar
hrchilds committed
1219 1220 1221 1222 1223 1224
    if (!PyArg_ParseTuple(args, "s", &visitProgram))
    {
        visitProgram = visitProgramDefault;
        PyErr_Clear();
    }
    debug1 << "Launch: 1: " << visitProgram << endl;
hrchilds's avatar
hrchilds committed
1225

hrchilds's avatar
hrchilds committed
1226 1227 1228
    //
    // Launch the viewer.
    //
hrchilds's avatar
hrchilds committed
1229
    LaunchViewer(visitProgram);
hrchilds's avatar
hrchilds committed
1230

hrchilds's avatar
hrchilds committed
1231 1232
    debug1 << "Launch: 2" << endl;

hrchilds's avatar
hrchilds committed
1233 1234 1235 1236 1237 1238 1239 1240 1241
    //
    // If the noViewer flag is false then the viewer could not launch.
    //
    if(noViewer)
    {
        VisItErrorFunc("VisIt's viewer could not launch!");
        return NULL;
    }

hrchilds's avatar
hrchilds committed
1242 1243
    debug1 << "Launch: 3" << endl;

hrchilds's avatar
hrchilds committed
1244 1245
    //
    // Wait for the viewer to tell us to load the plugins.
cyrush's avatar
cyrush committed
1246
    //
hrchilds's avatar
hrchilds committed
1247 1248
    DelayedLoadPlugins();

hrchilds's avatar
hrchilds committed
1249 1250
    debug1 << "Launch: 4" << endl;

hrchilds's avatar
hrchilds committed
1251 1252 1253 1254
    // Create the thread that listens for input from the viewer. Then
    // synchronize to flush out any initialization that came from the viewer
    // before we allow more commands to execute.
    CreateListenerThread();
hrchilds's avatar
hrchilds committed
1255
    debug1 << "Launch: 5" << endl;
hrchilds's avatar
hrchilds committed
1256
    int errorFlag = Synchronize();
hrchilds's avatar
hrchilds committed
1257
    debug1 << "Launch: 6" << endl;
hrchilds's avatar
hrchilds committed
1258 1259 1260 1261 1262 1263

    //
    // Initialize the extensions.
    //
    InitializeExtensions();

hrchilds's avatar
hrchilds committed
1264 1265
    debug1 << "Launch: 7" << endl;

hrchilds's avatar
hrchilds committed
1266 1267 1268 1269 1270 1271 1272
    //
    // Iterate over the plugins and add their methods to the VisIt module's
    // methods.
    //
    PlotPluginAddInterface();
    OperatorPluginAddInterface();

hrchilds's avatar
hrchilds committed
1273 1274 1275 1276 1277
    debug1 << "Launch: 8" << endl;

    //
    // Execute any client methods that came in during the Synchronize.
    //
1278
    debug1 << "Launch: 8, executing cached client methods." << endl;
bonnell's avatar
bonnell committed
1279
    size_t size = 0;
hrchilds's avatar
hrchilds committed
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
    do
    {
        ClientMethod *m = 0;

        MUTEX_LOCK();
        if(cachedClientMethods.size() > 0)
        {
            m = cachedClientMethods[0];
            cachedClientMethods.erase(cachedClientMethods.begin());
        }
        size = cachedClientMethods.size();
        MUTEX_UNLOCK();

        if(m != 0)
        {
            ExecuteClientMethod(m, false);
            delete m;
        }
    }
    while(size > 0);

    clientMethodsAllowed = true;

    debug1 << "Launch, end" << endl;

hrchilds's avatar
hrchilds committed
1305
    return IntReturnValue(errorFlag);
hrchilds's avatar
hrchilds committed
1306 1307 1308 1309 1310
}

// ****************************************************************************
// Function: visit_LaunchNowin
//
cyrush's avatar
cyrush committed
1311
// Purpose:
hrchilds's avatar
hrchilds committed
1312 1313 1314 1315 1316 1317 1318 1319
//   This is a Python callback that launches the viewer without a window.
//
// Note:       Only has an effect before the viewer is created.
//
// Programmer: Brad Whitlock
// Creation:   Tue Sep 18 14:04:06 PST 2001
//
// Modifications:
cyrush's avatar
cyrush committed
1320
//
hrchilds's avatar
hrchilds committed
1321 1322 1323 1324 1325 1326
// ****************************************************************************

STATIC PyObject *
visit_LaunchNowin(PyObject *self, PyObject *args)
{
    if(noViewer)
1327
        viewerArguments.push_back("-nowin"); //GetViewerProxy()->AddArgument("-nowin");
hrchilds's avatar
hrchilds committed
1328 1329 1330
    return visit_Launch(self, args);
}

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
// ****************************************************************************
// Function: visit_InitializeViewerProxy
//
// Purpose:
//   This is a Python callback that initializes a custom viewer proxy
//
// Note:       Only has an effect before the viewer is created.
//
// Programmer: Brad Whitlock
// Creation:   Tue Sep 18 14:04:06 PST 2001
//
// ****************************************************************************
PyObject *
visit_InitializeViewerProxy(PyObject *self, PyObject *args)
{
    if(noViewer)
    {
        long addy;
        if(!PyArg_ParseTuple(args, "l", &addy))
            return NULL;

        ViewerProxy* vp = (ViewerProxy*)((void*)addy);
        InitializeViewerProxy(vp);
    }
    else
    {
        VisItErrorFunc("VisIt's viewer is already launched!");
        return NULL;
    }

    Py_INCREF(Py_None);
    return Py_None;
}


hrchilds's avatar
hrchilds committed
1366 1367 1368
// ****************************************************************************
// Function: visit_SetDebugLevel
//
cyrush's avatar
cyrush committed
1369
// Purpose:
hrchilds's avatar
hrchilds committed
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
//   This is a Python callback that can be used to set the debug level that
//   the viewer uses.
//
// Note:       Only has an effect before the viewer is created.
//
// Programmer: Brad Whitlock
// Creation:   Tue Sep 18 14:04:06 PST 2001
//
// Modifications:
//
1380 1381
//    Mark C. Miller, Tue Apr 21 14:24:18 PDT 2009
//    Added logic to manage buffering of debug logs; an extra 'b' after level.
hrchilds's avatar
hrchilds committed
1382 1383
// ****************************************************************************

hrchilds's avatar
hrchilds committed
1384
PyObject *
hrchilds's avatar
hrchilds committed
1385 1386
visit_SetDebugLevel(PyObject *self, PyObject *args)
{
1387 1388
    char *sLevel = 0;
    if(!PyArg_ParseTuple(args, "s", &sLevel))
hrchilds's avatar
hrchilds committed
1389 1390
        return NULL;

1391 1392 1393 1394 1395 1396 1397 1398
    int dLevel = 0;
    if (isdigit(sLevel[0]))
        dLevel = atoi(sLevel);
    else
        return NULL;
    if (sLevel[1] == 'b')
        moduleBufferDebug = true;

hrchilds's avatar
hrchilds committed
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
    if(dLevel < 1 || dLevel > 5)
    {
        VisItErrorFunc("Valid debug levels are 1..5.");
        return NULL;
    }

    if(noViewer)
    {
        // Save the debug level.
        moduleDebugLevel = dLevel;

1410 1411
        //GetViewerProxy()->AddArgument("-debug");
        viewerArguments.push_back("-debug");
hrchilds's avatar
hrchilds committed
1412
        char tmp[10];
1413 1414 1415 1416
        if (moduleBufferDebug)
            SNPRINTF(tmp, 10, "%db", moduleDebugLevel);
        else
            SNPRINTF(tmp, 10, "%d", moduleDebugLevel);
1417 1418
        //GetViewerProxy()->AddArgument(tmp);
        viewerArguments.push_back(tmp);
hrchilds's avatar
hrchilds committed
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
    }
    else
    {
        VisItErrorFunc("Setting the debug level after the "
                     "viewer is launched has no effect.");
        return NULL;
    }

    Py_INCREF(Py_None);
    return Py_None;
}

// ****************************************************************************
// Function: visit_GetDebugLevel
//
cyrush's avatar
cyrush committed
1434
// Purpose:
hrchilds's avatar
hrchilds committed
1435 1436 1437 1438 1439 1440 1441 1442 1443
//   This is a Python callback that returns the debug level that the viewer
//   is using.
//
// Note:       Can be used before the viewer is launched.
//
// Programmer: Brad Whitlock
// Creation:   Tue Sep 18 14:04:06 PST 2001
//
// Modifications:
cyrush's avatar
cyrush committed
1444
//
hrchilds's avatar
hrchilds committed
1445 1446 1447 1448 1449
// ****************************************************************************

STATIC PyObject *
visit_GetDebugLevel(PyObject *self, PyObject *args)
{
hrchilds's avatar
hrchilds committed
1450
    NO_ARGUMENTS();
hrchilds's avatar
hrchilds committed
1451 1452 1453 1454
    return PyInt_FromLong(long(moduleDebugLevel));
}

// ****************************************************************************
whitlocb's avatar
whitlocb committed
1455
// Function: visit_GetLastError
hrchilds's avatar
hrchilds committed
1456
//
cyrush's avatar
cyrush committed
1457
// Purpose:
hrchilds's avatar
hrchilds committed
1458 1459 1460 1461 1462 1463
//   Returns the last error that VisIt sent back to the cli.
//
// Programmer: Brad Whitlock
// Creation:   Fri Jul 26 12:15:57 PDT 2002
//
// Modifications:
cyrush's avatar
cyrush committed
1464
//
hrchilds's avatar
hrchilds committed
1465 1466 1467 1468 1469
// ****************************************************************************

STATIC PyObject *
visit_GetLastError(PyObject *self, PyObject *args)
{
hrchilds's avatar
hrchilds committed
1470 1471
    NO_ARGUMENTS();

hrchilds's avatar
hrchilds committed
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
    const char *str = "";
    if(messageObserver)
        str = messageObserver->GetLastError().c_str();

    return PyString_FromString(str);
}

// ****************************************************************************
// Function: visit_LocalNameSpace
//
cyrush's avatar
cyrush committed
1482
// Purpose:
hrchilds's avatar
hrchilds committed
1483 1484 1485 1486 1487 1488 1489 1490
//   Determines how plugins are added to the Python namespace. If this
//   function is called, all the plugin methods are added to the top-level
//   as if "from visit import *" was specified.
//
// Programmer: Brad Whitlock
// Creation:   Fri Nov 9 19:00:31 PST 2001
//
// Modifications:
cyrush's avatar
cyrush committed
1491
//
hrchilds's avatar
hrchilds committed
1492 1493 1494
// ****************************************************************************

STATIC PyObject *
hrchilds's avatar
hrchilds committed
1495
visit_LocalNameSpace(PyObject *, PyObject *args)
hrchilds's avatar
hrchilds committed
1496
{
hrchilds's avatar
hrchilds committed
1497 1498
    NO_ARGUMENTS();

hrchilds's avatar
hrchilds committed
1499 1500 1501 1502 1503 1504 1505 1506
    localNameSpace = true;
    Py_INCREF(Py_None);
    return Py_None;
}

// ****************************************************************************
// Function: visit_GetLocalHostName
//
cyrush's avatar
cyrush committed
1507
// Purpose:
hrchilds's avatar
hrchilds committed
1508 1509 1510 1511 1512 1513
//   Returns the local host name.
//
// Programmer: Brad Whitlock
// Creation:   Thu Feb 21 10:09:52 PDT 2002
//
// Modifications:
cyrush's avatar
cyrush committed
1514
//
hrchilds's avatar
hrchilds committed
1515 1516 1517 1518 1519
// ****************************************************************************

STATIC PyObject *
visit_GetLocalHostName(PyObject *self, PyObject *args)
{
hrchilds's avatar
hrchilds committed
1520
    NO_ARGUMENTS();
hrchilds's avatar
hrchilds committed
1521
    return PyString_FromString(GetViewerProxy()->GetLocalHostName().c_str());
hrchilds's avatar
hrchilds committed
1522 1523 1524 1525 1526
}

// ****************************************************************************
// Function: visit_GetLocalUserName
//
cyrush's avatar
cyrush committed
1527
// Purpose:
hrchilds's avatar
hrchilds committed
1528 1529 1530 1531 1532 1533
//   Returns the user's login name.
//
// Programmer: Brad Whitlock
// Creation:   Thu Feb 21 10:09:52 PDT 2002
//
// Modifications:
cyrush's avatar
cyrush committed
1534
//
hrchilds's avatar
hrchilds committed
1535 1536 1537 1538 1539
// ****************************************************************************

STATIC PyObject *
visit_GetLocalUserName(PyObject *self, PyObject *args)
{
hrchilds's avatar
hrchilds committed
1540
    NO_ARGUMENTS();
hrchilds's avatar
hrchilds committed
1541
    return PyString_FromString(GetViewerProxy()->GetLocalUserName().c_str());
hrchilds's avatar
hrchilds committed
1542 1543 1544 1545 1546
}

// ****************************************************************************
// Function: visit_Close
//
cyrush's avatar
cyrush committed
1547
// Purpose:
hrchilds's avatar
hrchilds committed
1548 1549 1550 1551 1552 1553 1554 1555
//   This is a Python callback that closes the viewer.
//
// Note:       Only has an effect if the viewer is created.
//
// Programmer: John Bemis, Brad Whitlock
// Creation:   Tue Sep 18 14:04:06 PST 2001
//
// Modifications:
cyrush's avatar
cyrush committed
1556
//
hrchilds's avatar
hrchilds committed
1557 1558 1559 1560 1561
// ****************************************************************************

STATIC PyObject *
visit_Close(PyObject *self, PyObject *args)
{
hrchilds's avatar
hrchilds committed
1562 1563
    NO_ARGUMENTS();

hrchilds's avatar
hrchilds committed
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
    if(!noViewer)
    {
        CloseModule();
    }
    else
    {
        VisItErrorFunc("No viewer exists to be closed.");
        return NULL;
    }

    Py_INCREF(Py_None);
    return Py_None;
}

hrchilds's avatar
hrchilds committed
1578 1579 1580
// ****************************************************************************
// Function: LongFileName
//
cyrush's avatar
cyrush committed
1581
// Purpose:
hrchilds's avatar
hrchilds committed
1582 1583 1584 1585 1586 1587 1588
//   Converts a Windows short filename into a long filename.
//
// Arguments:
//   shortName : The short Windows name of the file.
//
// Returns:    The long windows name of the file.
//
cyrush's avatar
cyrush committed
1589
// Note:
hrchilds's avatar
hrchilds committed
1590 1591 1592 1593 1594
//
// Programmer: Brad Whitlock
// Creation:   Fri Dec 5 14:10:18 PST 2003
//
// Modifications:
cyrush's avatar
cyrush committed
1595
//
hrchilds's avatar
hrchilds committed
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
// ****************************************************************************

STATIC PyObject *
visit_LongFileName(PyObject *self, PyObject *args)
{
    char *fileName = 0;
    if(!PyArg_ParseTuple(args, "s", &fileName))
        return NULL;

#if defined(_WIN32)
    char *buf = new char[1000];
    PyObject *retval = 0;
    if(GetLongPathName(fileName, buf, 1000) != 0)
        retval = PyString_FromString(buf);
    else
        retval = PyString_FromString(fileName);
    delete [] buf;
    return retval;
#else
    return PyString_FromString(fileName);
#endif
}

hrchilds's avatar
hrchilds committed
1619 1620 1621 1622 1623 1624 1625 1626 1627 1628
//
// ViewerProxy methods.
//

// ****************************************************************************
// Function: visit_AddWindow
//
// Purpose:
//   Tells the viewer to add a window.
//
cyrush's avatar
cyrush committed
1629
// Notes:
hrchilds's avatar
hrchilds committed
1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643
//
// Programmer: John Bemis, Brad Whitlock
// Creation:   Mon Nov 12 12:15:53 PDT 2001
//
// Modifications:
//   Brad Whitlock, Mon Dec 30 13:10:54 PST 2002
//   I made it be synchronized.
//
// ****************************************************************************

STATIC PyObject *
visit_AddWindow(PyObject *self, PyObject *args)
{
    ENSURE_VIEWER_EXISTS();
hrchilds's avatar
hrchilds committed
1644
    NO_ARGUMENTS();
hrchilds's avatar
hrchilds committed
1645 1646

    MUTEX_LOCK();
hrchilds's avatar