File: main.cpp

package info (click to toggle)
gentle 1.9+cvs20100605+dfsg1-7
  • links: PTS, VCS
  • area: main
  • in suites: buster, sid
  • size: 12,224 kB
  • sloc: cpp: 41,569; ansic: 3,978; sh: 1,420; makefile: 240
file content (617 lines) | stat: -rwxr-xr-x 17,577 bytes parent folder | download | duplicates (3)
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
/** \file main.cpp
	\brief Contains global functions, includes, and the MyApp class
 */


/**	\mainpage GENtle - the source code documentation

	\section players The big players
	
	There are some classes that are of fundamental importance to understanding the GENtle code.
	<ul>
	<li>MyFrame - The base window of the whole application
 	<li>ChildBase - The "mother" of all modules, including the oddly named DNA module, MyChild
	<ul>
	<li>PlasmidCanvas - The colorful map used in the DNA and, partially, amino acid modules
	<li>SequenceCanvas - The universal sequence text class, used in most of the modules
	<ul>
	<li>SeqBasic - The base class for each "line type" in a SequenceCanvas, including DNA, amino acids, features, restriction enzymes, ABI peaks, etc.
	</ul>
	</ul>
    <li>TStorage - The class to communicate with databases
    <li>TVector - The class to store all sequence information, be it DNA or amino acids
    </ul>
	
*/

/////////////////////////////////////////////////////////////////////////////
// Name:        GENtle
// Purpose:     DNA/AA manipulation
// Author:      Magnus Manske
// Modified by:
// Created:     2002
// Copyright:   (c) Magnus Manske
// Licence:     GPL
/////////////////////////////////////////////////////////////////////////////

// ===========================================================================
// declarations
// ===========================================================================

// ---------------------------------------------------------------------------
// headers
// ---------------------------------------------------------------------------

// For compilers that support precompilation, includes "wx/wx.h".


#include "main.h"
#include <wx/tipdlg.h> 
#include <wx/splash.h>
#include <wx/filesys.h>
#include <wx/file.h>

#ifdef __WXMSW__
#include "wx/msw/registry.h"
#endif


using namespace std ;

IMPLEMENT_APP(MyApp)

#include <wx/arrimpl.cpp> // this is a magic incantation which must be done!
WX_DEFINE_OBJARRAY(wxArrayFloat);

// GLOBAL FUNCTIONS
int cmpint(int *first, int *second)
    {
    return *first > *second ;
    }    
    
int cmpre(TRestrictionEnzyme *first, TRestrictionEnzyme *second)
    {
    return first > second ; //????
    }    

void wxStringInsert ( wxString &s , int from , wxString t )
    {
    s = s.Mid ( 0 , from ) + t + s.Mid ( from ) ;
    }    

void explode ( wxString sep , wxString s , wxArrayString &r )
    {
    int a , b ;
    wxString n ;
    r.Clear () ;
    for ( a = 0 ; a + sep.Length() <= s.Length() ; a++ )
        {
        for ( b = 0 ; b < sep.Length() && s.GetChar(a+b) == sep.GetChar(b) ; b++ ) ;
        if ( b == sep.Length() )
           {
           r.Add ( n ) ;
           n = _T("") ;
           }
        else n += s.GetChar(a) ;
        }
    if ( !n.IsEmpty() ) r.Add ( n ) ; 
    }
    
wxString implode ( wxString sep , wxArrayString &r )
	{
	if ( r.GetCount() == 0 ) return _T("") ;
	wxString ret = r[0] ;
	for ( int a = 1 ; a < r.GetCount() ; a++ )
		ret += sep + r[a] ;
	return ret ;
	}

wxString txt ( char *item )
	{
	return txt ( wxString(item,wxConvUTF8) ) ;
	}

wxString txt ( wxString item )
    {
#ifndef __WXMSW__
	 if ( item.MakeUpper().Left(2) == _T("M_") )
	 {
		wxString s = myapp()->_text[item.MakeUpper()].Trim() ;
#ifdef __WXMAC__
		s.Replace ( _T("\tStrg-") , _T("\tCtrl-") ) ; // DE fix
#endif
		return s ;
	 }
#endif
    return myapp()->_text[item.MakeUpper()] ;
    }

// END GLOBAL FUNCTIONS


void MyApp::registerFileExtension ( wxString extension )
    {
#ifdef __WXMSW__    
    wxRegKey regKey;
    wxString idName(_T("HKEY_CLASSES_ROOT\\.")+extension);
    regKey.SetName(idName);    
  
    if ( !regKey.Exists() )
        {
        regKey.Create() ;
        regKey.SetValue ( _T("") , extension + _T("file") ) ;
        }    
  
    wxString s = _T("") , t = regKey ;
    s += _T("HKEY_CLASSES_ROOT\\") ;
    s += t ;
    s += _T("\\shell\\open\\command") ;
    regKey.SetName ( s ) ;

    if ( !regKey.Exists() ) regKey.Create () ;

    regKey.SetValue ( _T("") , _T("\"") + wxString ( myapp()->argv[0] ) + _T("\" \"%1\"") ) ;
#else
#endif
    }
    
void MyApp::registerProtocol ( wxString extension )
    {
#ifdef __WXMSW__    
    wxRegKey regKey;
    wxString idName(_T("HKEY_CLASSES_ROOT\\")+extension);
    regKey.SetName(idName);    
  
    if ( !regKey.Exists() )
        {
        regKey.Create () ;
        regKey.SetValue ( _T("") , _T("URL: GENtle Protocol") ) ;
        regKey.SetValue ( _T("URL Protocol") , _T("") ) ;
        }    
  
    wxString s , t = regKey ;
    s += _T("HKEY_CLASSES_ROOT\\") ;
	 s += extension ;
    s += _T("\\shell\\open\\command") ;
    regKey.SetName ( s ) ;

    if ( !regKey.Exists() ) regKey.Create () ;

    regKey.SetValue ( _T("") , _T("\"") + wxString ( myapp()->argv[0] ) + _T("\" \"%1\"") ) ;
#else
#endif
    }

MyApp *theapp ; /**< \var theapp Pointer to the current application. */

MyApp *myapp ()
   {
   return theapp ;
   }


// ---------------------------------------------------------------------------
// MyApp
// ---------------------------------------------------------------------------

/**	\fn MyApp::OnInit()
	\brief Initializes the application.
	
	* - Initializes variables
	* - Initializes handlers
	* - Checks if another program instance is already running
	* - Creates a new local database, if necessary
	* - Creates the frame
	* - Shows the splash screen
	* - Shows Tip of the Day (currently deactivated)
	* - Registers file extensions
*/
bool MyApp::OnInit()
{
   isoconv = new wxCSConv ( _T("iso-8859-1") ) ;
   wxConvCurrent = isoconv ;
   errout = NULL ;
   total_log_time = 0 ;
   total_log_counter = 0 ;
#ifdef MYLOG
    wxStartTimer() ;
#endif

	wxString s1 , s2 ;
	wxFileName::SplitPath ( argv[0] , &homedir , &s1 , &s2 ) ;

#ifdef __WXMSW__
   if ( homedir.IsEmpty() ) homedir = wxGetCwd() ;
#endif

#ifdef __WXMAC__
   homedir = homedir.BeforeLast ( '/' ) ;
   homedir += _T("/Resources") ;

   wxApp::s_macAboutMenuItemId = MDI_ABOUT;
   wxApp::s_macPreferencesMenuItemId = PROGRAM_OPTIONS;
   wxApp::s_macExitMenuItemId = MDI_QUIT;
//	wxApp::s_macHelpMenuTitleName = "Help";
	
#endif

#ifdef __DEBIAN__
	homedir = _T("/usr/share/gentle") ;
#endif

   wxInitAllImageHandlers() ;
   wxFileSystem::AddHandler ( new wxInternetFSHandler ) ;

   wxSetWorkingDirectory ( homedir ) ; // Setting home directory as working dir
	
	// Setting ncoils dir as an environment variable
   wxString ncoilsdir ;
   ncoilsdir = _T("COILSDIR=") ;
   ncoilsdir += homedir ;

#ifdef __WXMAC__	
	if ( wxGetEnv ( _T("COILSDIR") , NULL ) ) wxUnsetEnv ( _T("COILSDIR") ) ;
	wxSetEnv ( _T("COILSDIR") , homedir ) ;
#else
	setenv ( "COILSDIR" , homedir.c_str() , 1 ) ;
#endif	

	
    // Is an instance already running?
    const wxString name = wxString::Format ( _T("GENtle-%s") , wxGetUserId().c_str());
    m_checker = new wxSingleInstanceChecker (name);
    if ( m_checker->IsAnotherRunning() )
    {
        wxLogError(_T("Another program instance is already running, aborting."));
        return false;
    }
    theapp = this ;
    dbWarningIssued = false ;
    programVersion = 0 ; // This ensures that no old program version messes with a new database scheme

    wxFileSystem::AddHandler(new wxInternetFSHandler);
    
    // Create the main frame window
#ifdef __WXMSW__
    slash = _T("\\") ;
#else
    slash = _T("/") ;
#endif

#ifdef __WXMAC__
	bmpdir = homedir ;
#else
    bmpdir = homedir + slash + _T("bitmaps") ;
#endif
	
	// Make sure local database exists
    wxString localdb , blankdb ;
    localdb = getLocalDBname() ;
    blankdb = homedir + slash + _T("blank.db") ;
    wxLogNull logNo; // Suppress error message
    if ( !wxFileExists ( localdb ) && wxFileExists ( blankdb ) )
    	{
		wxCopyFile ( blankdb , localdb ) ;
		}
	
	// Check is local.db exists and is writable
	bool local_ok = true ;
	if ( !wxFileExists ( localdb ) ) local_ok = false ;
	else
		{
		wxFile test ( localdb , wxFile::write_append ) ;
		if ( !test.IsOpened() ) local_ok = false ;
		}
	if ( !local_ok )
		{
		theRealLocalDb = wxGetHomeDir() + myapp()->slash + _T("local.db") ;
		localdb = theRealLocalDb ;
		if ( !wxFileExists ( localdb ) )
			{
			wxCopyFile ( blankdb , localdb ) ;
			}
		else local_ok = true ;
		}

	frame = new MyFrame((wxFrame *)NULL, -1, _T(""),
                        wxPoint(-1, -1), wxSize(500, 400),
                        wxDEFAULT_FRAME_STYLE );    
    frame->initme () ;
    if ( frame->dying ) return FALSE ;
    SetTopWindow(frame);

	if ( clp[_T("no-splash-screen")] == _T("1") )
		frame->showSplashScreen = false ;

	if ( !local_ok )
		wxMessageBox ( txt("t_local_db_warning") ) ;

	
    if ( frame->showSplashScreen )
        {
        wxBitmap bitmap;
        wxString bmpfile = bmpdir + slash + _T("splash.bmp") ;
        if (bitmap.LoadFile(bmpfile, wxBITMAP_TYPE_BMP))
            {
            //wxSplashScreen* splash = 
			new wxSplashScreen(bitmap,
            wxSPLASH_CENTRE_ON_SCREEN|wxSPLASH_TIMEOUT,
            2500, NULL, -1, wxDefaultPosition, wxDefaultSize,
            wxSIMPLE_BORDER|wxSTAY_ON_TOP);
            }
        wxYield();
        }

    // Tips turned off until I can figure out how the hell
    // to get the state of the !"$%& show-again-checkbox
    bool showTip = frame->LS->getOption ( _T("SHOWTIP") , true ) ;

	if ( clp[_T("no-tips")] == _T("1") )
		showTip = false ;

    if ( showTip )
        {
        int tip = frame->LS->getOption ( _T("NEXTTIP") , 0 ) ;
        wxString tipfile = _T("tips_") ;
        tipfile += frame->lang_string ;
        tipfile += _T(".txt") ;
        wxTipProvider *tipProvider = wxCreateFileTipProvider(tipfile, tip);
        showTip = wxShowTip(frame, tipProvider, showTip);
//        showTip = tipProvider->ShowTipsOnStartup() ;
        tip = tipProvider->GetCurrentTip() ;
//        frame->LS->setOption ( "SHOWTIP" , showTip ) ;
        frame->LS->setOption ( _T("NEXTTIP") , tip ) ;
        frame->LS->setOption ( _T("SHOWTIP") , showTip ) ;
        delete tipProvider;
        }
        
    if ( frame->doRegisterStuff )
    	{
        registerFileExtension ( _T("gb") ) ;
        registerFileExtension ( _T("genbank") ) ;
        registerFileExtension ( _T("gbxml") ) ;
        registerFileExtension ( _T("fasta") ) ;
        registerFileExtension ( _T("clone") ) ;
        registerFileExtension ( _T("abi") ) ;
        registerFileExtension ( _T("ab1") ) ;
        registerFileExtension ( _T("seq") ) ;
        registerFileExtension ( _T("gcg") ) ;
        registerFileExtension ( _T("codata") ) ;
        registerFileExtension ( _T("NBRF_PIR") ) ;
        registerFileExtension ( _T("swissprot") ) ;
        registerProtocol ( _T("gentle") ) ;
        }    

    return TRUE;
}

wxString MyApp::getLocalDBname ()
	{
	if ( !theRealLocalDb.IsEmpty() ) return theRealLocalDb ;
#ifdef __WXMAC__
	theRealLocalDb = wxGetHomeDir() + myapp()->slash + _T("local.db") ;
#else
	theRealLocalDb = myapp()->homedir + myapp()->slash + _T("local.db") ;
#endif
	return theRealLocalDb ;
	}

wxString MyApp::get_GENtle_version ()
	{
 	return wxString::Format ( _T("%d.%d.%d") , GENTLE_VERSION_MAJOR ,
  											GENTLE_VERSION_MINOR , 
  											GENTLE_VERSION_SUB ) ;
	}    

/**	\fn MyApp::OnExit ()
	\brief Exits the application.
	
	* - Finished a log, if one is written
	* - deletes the wxSingleInstanceChecker
*/
int MyApp::OnExit ()
    {
#ifdef MYLOG
    logout->Write ( _T("Total log time : ") + wxString::Format ( _T("%d ms") , total_log_time ) + _T("\n") ) ;
    logout->Flush() ;
#endif
    delete m_checker;
	return wxApp::OnExit () ;
//    return 0;
    }

void MyApp::launchBrowser ( wxString url )
	{
//	wxMessageBox ( url ) ;
//	if ( wxLaunchDefaultBrowser ( url ) ) return ;
    wxString command = myapp()->getHTMLCommand ( url ) ;
    wxExecute ( command ) ;
	}

/**	\fn MyApp::getHTMLCommand ( wxString command )
	\brief Returns the command line to invoke the browser.
	\param command The URL/file.
*/
wxString MyApp::getHTMLCommand ( wxString command )
    {
#ifdef __WXMAC__
	return _T("open ") + command ;
#endif
    wxString ret ;
    ret = getFileFormatCommand ( command , _T("html") ) ;
    if ( ret.IsEmpty() ) ret = getFileFormatCommand ( command , _T("htm") ) ;
    if ( !ret.IsEmpty() ) return ret ;

// Fallback
#ifdef __WXMSW__    
    wxRegKey regKey;
    wxString idName(_T("HKEY_CLASSES_ROOT\\.html"));
    regKey.SetName(idName);    
    wxString s , t = regKey ;
    s += _T("HKEY_CLASSES_ROOT\\") ;
    s += t ;
    s += _T("\\shell\\open\\command") ;
    regKey.SetName ( s ) ;
    wxString q = regKey ;
    regKey.Close();
    q.Replace ( _T("-nohome") , _T("") ) ;
    if ( 0 == q.Replace ( wxString ( _T("%1") ) , command ) )
        q += _T(" \"") + command + _T("\"") ;
    return q ;
#else
    return _T("") ;
#endif
    }

/**	\fn MyApp::getFileFormatCommand ( wxString command )
	\brief Returns the command line to invoke the application.
	\param type The file ending to find the application for.
	\param file The URL/file.
*/
wxString MyApp::getFileFormatCommand ( wxString type , wxString file )
	{
    wxFileType *ft = mtm.GetFileTypeFromExtension ( type ) ;
    if ( !ft ) return _T("") ;
    return ft->GetOpenCommand ( file ) ;
	}    
    
/**	\fn MyApp::getFileFormatApplication ( wxString type )
	\brief Returns the application associated with a file type. Windows only.
	\param type The file ending to find the application for.
*/
wxString MyApp::getFileFormatApplication ( wxString type )
    {
#ifdef __WXMSW__    
    wxRegKey regKey;
    wxString idName(_T("HKEY_CLASSES_ROOT\\."));
    idName += type ;
    regKey.SetName(idName);    
    wxString s , t = regKey ;
    s += _T("HKEY_CLASSES_ROOT\\") ;
    s += t ;
    s += _T("\\shell\\open\\command") ;
    regKey.SetName ( s ) ;
    wxString q = regKey ;
    regKey.Close();
    q.Replace ( wxString ( _T("%1") ) , _T("") ) ;
    return q ;
#else
    return _T("") ;
#endif
    }

/**	\fn MyApp::do_my_ass ( bool b , wxString msg )
	\brief "My assertion" - little inside joke...
	\param b The condition given in the call. No assertion when b is FALSE.
	\param msg The message string to write into errout.
	
	The function writes the text of "msg" to the ERROR.txt file
	in case "b" is true. This is done to catch possible out-of-range errors.
	The function should not be used in releases, as the mere out-of-range check
	might significantly impact on performance. Called as "myass" (see main.h defs).
*/
void MyApp::do_my_ass ( bool b , wxString msg )
    {
    if ( b ) return ;
    if ( !errout ) errout = new wxFile ( _T("ERROR.txt") , wxFile::write ) ;
    errout->Write ( msg + _T("\n") ) ;
    errout->Flush() ;
    }
    
/**	\fn MyApp::do_my_log ( wxString function , wxString msg )
	\brief Logs events to a file.
	\param function The originating function name of the log event.
	\param msg The message string to write into logout.
	
	The function writes the text of "msg" to the LOG.txt file
	together with the "function" name. This is done to log events and
	variable values at certain points in the code. This should not
	be used in releases, as it <b>will</b> severely impact on
	performance. Called as "mylog" (see main.h defs).
*/
void MyApp::do_my_log ( wxString function , wxString msg )
    {
    if ( !logout ) logout = new wxFile ( _T("LOG.txt") , wxFile::write ) ;
    if ( total_log_counter > 5000 )
    	{
	    logout->Close () ;
	    logout->Open ( _T("LOG.txt") , wxFile::write ) ;
	    total_log_counter = 0 ;
    	}
    total_log_counter++ ;

    int i = sw.Time() ;
    total_log_time += i ;
    logout->Write ( function + _T(" : ") + msg + _T(" (") + wxString::Format ( _T("%d ms") , i ) + _T(")\n") ) ;
    logout->Flush() ;
    }

/** \fn MyApp::init_txt ( wxString lang , wxString csv , wxHashString *target , int ln )
	\brief Initializes a hash table from a CSV file
	\param lang the column identifier (first row of the CSV file)
	\param csv the CSV file
	\param target the hash table; if NULL (default), the language table is created
	\param ln the default language number
*/
void MyApp::init_txt ( wxString lang , wxString csv , wxHashString *target , int ln )
    {
    if ( !target ) target = &_text ;
    wxTextFile in ( myapp()->homedir + _T("/") + csv) ;
    in.Open ( wxConvUTF8 ) ;
//    in.Open ( *isoconv ) ;
//    unsigned char t[10000] ;
    bool firstline = true ;
    TGenBank dummy ;

/*
#ifdef __WXGTK__
	wxMBConv *conv = &wxConvUTF8 ;
#else
	wxMBConv *conv = isoconv ;
#endif
*/

    for ( int lc = 0 ; lc < in.GetLineCount() ; lc++ )
        {
		wxString s = in[lc] ;
		if ( s.IsEmpty() ) continue ; // Blank line
		wxArrayString v ;
		s.Replace ( _T("\\t") , _T("\t") ) ;
		s.Replace ( _T("\\n") , _T("\n") ) ;
		s = s.Mid ( 1 ) ; // Get rid of initial "
		while ( 1 )
			{
			int f = s.Find ( _T("\",\"") ) ;
			if ( f == -1 )
				{
				s = s.Left ( s.length()-1 ) ; // Get rid of final "
				v.Add ( s ) ;
				break ;
				}
			else
				{
				v.Add ( s.Left ( f ) ) ;
				s = s.Mid ( f + 3 ) ;
				}
			}

		// Get key (firstline) or value
        if ( firstline )
           {
           if ( frame->language_list.IsEmpty() )
		   	{
			frame->language_list = v ;
			frame->language_list.RemoveAt ( 0 ) ;
			}
           for ( int a = 0 ; a < v.GetCount() ; a++ )
              if ( v[a].Upper() == lang.Upper() )
                 ln = a ;
           }
        else if ( v.GetCount() > ln )
           {
           if ( v[ln].Find ( '\t' ) > -1 ) v[ln] += _T(" ") ;
           (*target)[v[0].MakeUpper()] = v[ln] ;
           }
        firstline = false ;
        }
    }