source: palm/trunk/SCRIPTS/palmrungui @ 4470

Last change on this file since 4470 was 4470, checked in by maronga, 4 years ago

funtionality improvements in palmrungui

  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 63.6 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3#--------------------------------------------------------------------------------#
4# This file is part of the PALM model system.
5#
6# PALM is free software: you can redistribute it and/or modify it under the terms
7# of the GNU General Public License as published by the Free Software Foundation,
8# either version 3 of the License, or (at your option) any later version.
9#
10# PALM is distributed in the hope that it will be useful, but WITHOUT ANY
11# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13#
14# You should have received a copy of the GNU General Public License along with
15# PALM. If not, see <http://www.gnu.org/licenses/>.
16#
17# Copyright 1997-2018  Leibniz Universitaet Hannover
18#--------------------------------------------------------------------------------#
19#
20# Current revisions:
21# -----------------
22#
23#
24# Former revisions:
25# -----------------
26# $Id: palmrungui 4470 2020-03-24 06:52:19Z maronga $
27# Added file size output, more I/O functionalities, new/removed buttons
28#
29# 4428 2020-02-27 11:43:53Z maronga
30# Bugfix for update button
31#
32# 4427 2020-02-27 11:29:51Z maronga
33# Small fixes and adjustments
34#
35# 4420 2020-02-24 14:13:56Z maronga
36# Bugfix: minor fixes related to start buttons
37#
38# 4411 2020-02-18 14:28:02Z maronga
39# Added new features: individual tag for submitted runs, automatic finding of
40# configuration, start of palmbuild from GUI
41#
42# 4405 2020-02-12 19:11:11Z maronga
43# Major revisions: New layout. Merged with palm job manager (palm_jm).
44# Minor revisions: Misc. bugs fixed.
45#
46# 4394 2020-02-04 21:40:38Z maronga
47# Bugfix: harmonized naming convention of configuration files
48#
49# 4393 2020-02-04 21:24:48Z maronga
50# Removed PALM_BIN dependency and os calls
51#
52# 3487 2018-11-05 07:18:02Z maronga
53# Renamed options -d and -h to -r and -c.
54#
55# 2825 2018-02-20 21:48:27Z maronga
56# Adjusted to work with newest version of palmrun
57#
58# 2718 2018-01-02 08:49:38Z maronga
59# Corrected "Former revisions" section
60#
61# 2696 2017-12-14 17:12:51Z kanani
62# Change in file header (GPL part)
63#
64# 2484 2017-09-20 14:22:42Z maronga
65# Added PALM logo
66#
67# 2480 2017-09-19 06:24:14Z maronga
68# option -A (project account number) added
69#
70# 2477 2017-09-18 08:42:29Z maronga
71# Renamed restart run appendix from "f" to "r". Bugfix for displaying restart runs.>
72# Revised list of recently submitted jobs
73#
74# 2413 2017-09-06 12:48:29Z maronga
75# Renamed to palmrungui and adapted for use with palmrun instead of mrun.
76#
77# 2316 2017-07-20 07:53:42Z maronga
78# Initial revision in python
79#
80#
81#
82# Description:
83# ------------
84# Graphical user interface for the palmrun script.
85# @author Felix Gaschler
86# @author Björn Maronga (maronga@muk.uni-hannover.de)
87#
88# Instructions:
89# -------------
90#
91#------------------------------------------------------------------------------!
92
93import sys
94import subprocess
95from PyQt4 import QtCore, QtGui, uic
96from PyQt4.QtCore import QProcess,pyqtSlot,SIGNAL,SLOT
97from time import strftime
98import os
99import shutil
100
101global update_frequency
102update_frequency = 5*60000
103
104# Determine PALM directories
105try: 
106   devnull = open(os.devnull, 'w')     
107   palm_dir = os.getcwd()
108   palm_bin = palm_dir + '/trunk/SCRIPTS'
109   palm_source = palm_dir + '/trunk/SOURCE'
110   job_dir = palm_dir + '/JOBS'
111   user_dir = palm_dir + '/USER_CODE'
112   with open(palm_bin + '/palmrungui', 'r') as fh:
113      # file found
114      out = None
115except:   
116   print "Error. palmrungui probably called in wrong directory."
117   raise SystemExit
118
119
120# returns the human readable file size of filename
121def file_size(filename, suffix='B'):
122   size_raw = os.stat(filename).st_size
123   for unit in [' ',' K',' M',' G',' T']:
124      if abs(size_raw) < 1024.0:
125         return "%i%s%s" % (size_raw, unit, suffix)
126      size_raw /= 1024.0
127   return "%.1f%s%s" % (num, 'Y', suffix)
128
129
130
131palmrunline = ""
132set_list = []
133
134Ui_MainWindow = uic.loadUiType("%s/palmrungui_files/mainwindow.ui" % (palm_bin))[0]
135Ui_helpDialog = uic.loadUiType("%s/palmrungui_files/help.ui" % (palm_bin))[0]
136Ui_aboutDialog = uic.loadUiType("%s/palmrungui_files/about.ui" % (palm_bin))[0]
137
138class HelpDialog(QtGui.QDialog,Ui_helpDialog):
139    def __init__(self, parent=None):
140        super(HelpDialog,self).__init__()
141        self.setupUi(self)
142       
143class AboutDialog(QtGui.QDialog,Ui_aboutDialog):
144    def __init__(self, parent=None):
145        super(AboutDialog,self).__init__()
146        self.setupUi(self)       
147
148class Mainwindow(QtGui.QMainWindow, Ui_MainWindow):
149    def __init__(self, parent=None):
150        super(Mainwindow, self).__init__()
151        self.setupUi(self)
152   
153        self.palm_logo.setPixmap(QtGui.QPixmap(palm_bin + "/palmrungui_files/logo.png"))       
154       
155        with open(palm_bin + "/palmrungui") as search:
156           for line in search:
157              line = line.rstrip()
158              if "$Id" in line:
159                 version = "Version: r" + line.split(" ")[3] + " (" + line.split(" ")[4] + ")"
160                 self.groupBox.findChild(QtGui.QLabel,"label_version").setText(version)
161                 break
162       
163        self.recent_jobs(50)
164        self.load_jobs()
165
166        # look up configuration files and add to combo box
167       
168        self.group_execution.findChild(QtGui.QComboBox,"combo_configuration").addItem("")
169       
170        for files in os.listdir(palm_dir):
171           if files.startswith(".palm.config"):
172              tmpstring = filter(None,files.split(".palm.config."))[0]
173              self.group_execution.findChild(QtGui.QComboBox,"combo_configuration").addItem(tmpstring)
174
175        commandline = self.groupBox.findChild(QtGui.QLineEdit,"commandline")
176        commandline.setText("")
177       
178        self.tabWidget.setCurrentIndex(0) 
179       
180       
181        filename = "%s/.palmrungui.default" % (palm_dir) 
182        if os.path.exists(filename):
183            pass
184        else:
185            return
186       
187        file = open(filename, "r")
188        if ( file is not None ):
189            # File opened successfully
190            palmrunline = file.readline()
191            #if neue zeile zeichen
192            palmrunline = palmrunline[:len(palmrunline)-1]
193            file.close() 
194
195        # In case a palmrunline was found, load it to mainwindow
196        if ( palmrunline != ""):
197            palmrunline = palmrunline[17:] 
198            commandline.setText(palmrunline)
199            self.setup_gui(palmrunline)
200
201
202        QtGui.QApplication.processEvents()
203
204
205        # Start refresh timer. On timeout perform update
206        self.timer = QtCore.QTimer(self)
207        self.timer.timeout.connect(self.update_all)
208        self.timer.setSingleShot(False)
209        self.timer.start(update_frequency)
210
211        # The timetimer counts the time since last update
212        self.timetimer= QtCore.QElapsedTimer()
213        self.timetimer.start()
214
215        # The labeltimer induces the update of the remaining time in the UI
216        self.labeltimer = QtCore.QTimer(self)
217        self.labeltimer.timeout.connect(self.UpdatePush)
218        self.labeltimer.setSingleShot(False)
219
220        # Update in the UI will be performed at each 1/10 of the update interval
221        self.labeltimer.start(update_frequency/10)
222        self.push_update.setText("Update (" + str(int(update_frequency/1000/60)) + " min)")
223
224    # starts xterm with palmrun commandline
225    #######################################
226    def startpalmrun(self):
227        palmrunline = str(self.groupBox.findChild(QtGui.QLineEdit,"commandline").text())
228        userline    = str(self.group_advanced.findChild(QtGui.QLineEdit,"line_user").text())
229       
230        # Check for empty line
231        palmrunline_save = palmrunline
232        if (userline != ""):
233            palmrunline = "%s %s" % (palmrunline,userline)
234        history_line = palmrunline       
235       
236        # Disable the main window
237        self.tabWidget.setEnabled(False)
238        self.groupBox.findChild(QtGui.QPushButton,"button_start").setEnabled(False)
239        self.groupBox.findChild(QtGui.QLineEdit,"line_tag").setEnabled(False)
240        self.groupBox.findChild(QtGui.QPushButton,"button_start").setText("wait...")     
241        self.groupBox.findChild(QtGui.QLineEdit,"commandline").setText("Executing palmrun in xterm...")       
242
243        # Wait until all commands have been executed (ugly) ?
244        #for i in range(0,21):
245        #    qApp->processEvents()       
246
247        # Start xterm as QProcess
248        palmrun = QProcess()
249        palmrun.setProcessChannelMode(QProcess.MergedChannels) # mergedChannels
250        palmrun.setWorkingDirectory(palm_dir)
251
252        geomet = self.frameGeometry()
253
254        posx = geomet.x()+geomet.width()
255        posy = geomet.y()
256
257        if ( os.path.isfile("palmrungui.log") ):
258           os.remove("palmrungui.log")
259
260        s = " -title \"Executing palmrun...\" -fa \"Monospace\" -l -lf \"palmrungui.log\" -fs 11 -geometry \"80x38+%d+%d\" -e \"" % (posx,posy)
261        palmrunline = "%s%s ;echo -n '--> Press enter to continue...';read yesno\"</dev/stdin" % (s, palmrunline.replace("\"","\'"))
262
263        mString = "xterm %s" % (palmrunline)
264        palmrun.start(mString)
265
266        if( palmrun.waitForStarted() is False ):
267            return
268
269        # Wait until palmrun has finished or wait for 200 minutes
270        palmrun.waitForFinished(3600000)       
271
272        # Jobs has been submitted or aborted. Continuing...
273        # Save the palmrun command to history file
274        filename = "%s/.palmrungui.history" % (palm_dir)
275        tmstamp = strftime("%Y/%m/%d %H:%M")
276        tag = str(self.groupBox.findChild(QtGui.QLineEdit,"line_tag").text())
277   
278        file = open(filename,"a")
279        s = "%s %s (%s)\n" % (tmstamp,history_line,tag)
280        file.write(s)
281        file.close()             
282       
283        # Enable main window again
284        self.tabWidget.setEnabled(True)
285        self.groupBox.findChild(QtGui.QPushButton,"button_start").setEnabled(True)
286        self.groupBox.findChild(QtGui.QPushButton,"button_start").setText("palmrun") 
287        self.groupBox.findChild(QtGui.QLineEdit,"commandline").setText(palmrunline_save)
288        self.groupBox.findChild(QtGui.QLineEdit,"line_tag").setEnabled(True)
289       
290        # Reload recent jobs
291        self.recent_jobs(50)
292       
293       
294       
295    # Update the label
296    def UpdatePush(self):
297        remaining_time = (update_frequency - self.timetimer.elapsed()) / 1000 / 60
298        self.push_update.setText("Update (" + str(remaining_time) + " min)")
299
300
301    # starts xterm with palmbuild commandline
302    #######################################
303    def startpalmbuild(self):
304        palmbuildline = 'palmbuild -c ' + str(self.group_execution.findChild(QtGui.QComboBox, "combo_configuration").currentText())
305
306        full_build = self.group_execution.findChild(QtGui.QCheckBox,"check_rebuild").checkState()
307
308        if ( full_build == 2 ):
309           for filename in os.listdir(palm_source):
310              os.utime(palm_source + "/" + filename, None)
311
312        palmrunline_save = str(self.groupBox.findChild(QtGui.QLineEdit,"commandline").text())
313
314        # Disable the main window
315        palmbuildline_save = palmbuildline
316        self.tabWidget.setEnabled(False)
317        self.groupBox.findChild(QtGui.QPushButton,"button_start").setEnabled(False)
318        self.groupBox.findChild(QtGui.QLineEdit,"line_tag").setEnabled(False) 
319        self.groupBox.findChild(QtGui.QPushButton,"button_start").setText("wait...") 
320        self.group_execution.findChild(QtGui.QPushButton,"button_palmbuild").setText("wait...") 
321        self.groupBox.findChild(QtGui.QLineEdit,"commandline").setText("Executing palmbuild in xterm...")       
322       
323        # Wait until all commands have been executed (ugly) ?
324        #for i in range(0,21):
325        #    qApp->processEvents()       
326       
327        # Start xterm as QProcess
328        palmbuild = QProcess()
329        palmbuild.setProcessChannelMode(QProcess.MergedChannels) # mergedChannels
330        palmbuild.setWorkingDirectory(palm_dir)
331   
332        geomet = self.frameGeometry()
333       
334        posx = geomet.x()+geomet.width()
335        posy = geomet.y()
336     
337        s = " -title \"Executing palmbuild...\" -fa \"Monospace\" -fs 11 -geometry \"80x38+%d+%d\" -e \"" % (posx,posy)
338        palmbuildline = "%s%s;echo -n '--> Press enter to continue...';read yesno\"</dev/stdin" % (s, palmbuildline.replace("\"","\'"))
339       
340        mString = "xterm %s" % (palmbuildline)
341        palmbuild.start(mString)
342   
343        if( palmbuild.waitForStarted() is False ):
344            return
345       
346        # Wait until palmbuild has finished or wait for 200 minutes
347        palmbuild.waitForFinished(3600000)       
348       
349         
350       
351        # Enable main window again
352        self.tabWidget.setEnabled(True)
353        self.groupBox.findChild(QtGui.QPushButton,"button_start").setEnabled(True)
354        self.groupBox.findChild(QtGui.QLineEdit,"line_tag").setEnabled(True)
355        self.groupBox.findChild(QtGui.QPushButton,"button_start").setText("palmrun") 
356        self.groupBox.findChild(QtGui.QLineEdit,"commandline").setText(palmrunline_save)
357        self.group_execution.findChild(QtGui.QPushButton,"button_palmbuild").setText("(re-)build")     
358        # Reload recent jobs
359        self.recent_jobs(50)
360
361    # loads recent jobs
362    ######################################
363    def recent_jobs(self, number):
364        fileDir = "%s/.palmrungui.history" % (palm_dir)
365        if os.path.exists(fileDir):
366            pass
367        else:
368            return
369
370        file = open(fileDir,"r")
371        history = file.readlines()
372        tmphistory = list()
373        tmptag = list()
374        file.close()
375        j = 0
376
377        list_jobname = self.group_history.findChild(QtGui.QListWidget,"list_jobname")
378        list_jobname.clear()
379
380        # Read history entries and append to recent job list
381        i=len(history)-1
382        count = 0
383        while i>=0 and count<number:
384            timestamp = history[i][:16]
385            listitem = history[i][17:len(history[i])-1]
386            tagitem = listitem
387            configitem = listitem
388            matchitems = list_jobname.findItems(listitem, QtCore.Qt.MatchExactly)
389
390            if ( len(matchitems) == 0 ):
391                listitem = filter(None,listitem.split(" -r"))[1]
392                listitem = listitem.strip()
393                listitem = filter(None,listitem.split(" "))[0]
394                listitem = listitem.replace("\"","") 
395                list_jobname.addItem(listitem)
396               
397                configitem = filter(None,configitem.split(" -c"))[1]
398                configitem = configitem.strip()
399                configitem = filter(None,configitem.split(" "))[0]
400                configitem = configitem.replace("\"","") 
401
402                s = "%s: %s (%s)" % (timestamp,listitem,configitem)
403                tmphistory.append(s)
404               
405               
406                tagitem = filter(None,tagitem.split(" ("))[1]
407                tagitem = tagitem.replace(")","") 
408                if ( len(tagitem) == 0 ): 
409                   s = "Tag: empty"
410                else:
411                   s = "Tag: %s" % (tagitem)               
412                tmptag.append(s)
413                count = count +1
414
415                j = j+1
416               
417            if ( j == number ):
418                break
419            i = i-1
420           
421        # Send to list
422        list_jobname.clear()
423       
424        i=0
425        while i<len(tmphistory):
426            list_jobname.addItem(tmphistory[i])
427            list_jobname.item(i).setToolTip(tmptag[i])
428            i = i+1
429           
430
431    # Enables coupled settings
432    ###############################
433    def enable_coupled(self):
434        coupledState = self.group_execution.findChild(QtGui.QComboBox, "drop_job").currentText()
435        group = self.group_execution.findChild(QtGui.QGroupBox, "group_coupled")
436       
437        if (coupledState == "Restart run (coupled atmosphere ocean)" or coupledState == "Initial run (coupled atmosphere ocean)"):
438            self.group_coupled.setEnabled(True)
439        else: 
440            self.group_coupled.setEnabled(False)
441           
442
443    # select a job via click from list
444    #################################
445    def choosejob_list(self):
446        #  Get selected item from list
447        list_jobname = self.group_history.findChild(QtGui.QListWidget,"list_jobname")
448        filename = str(list_jobname.currentItem().text())
449
450        timestamp = filename[:16]
451        jobname = filename[18:].split(" ")[0]
452
453        itemint = list_jobname.currentRow()
454
455        # Reload list
456        self.recent_jobs(50)
457        self.load_jobs()
458   
459        # Set selected item to jobname
460        list_jobname.item(itemint).setSelected(True)
461   
462        # Set selected item to jobname in "available jobs" list
463        item2int = self.list_jobs.findItems(jobname,QtCore.Qt.MatchCaseSensitive)
464       
465        if ( item2int != [] ):
466           self.list_jobs.setCurrentItem(item2int[0])
467        self.update_input()
468           
469   
470        fileDir = "%s/.palmrungui.history" % (palm_dir)
471        file = open(fileDir,"r")
472        history = file.readlines()
473        tmphistory = list()
474        file.close()       
475   
476        i = len(history)
477        while i>=1:
478            listitem = history[i-1][17:len(history[i-1])-1]
479            listitem = filter(None,listitem.split(" -r"))[1]
480            listitem = listitem.strip()
481            listitem = filter(None,listitem.split(" "))[0]
482            listitem = listitem.replace("\"","") 
483
484            # Select command line with correct timestamp and jobname
485            if (history[i-1][:16] == timestamp and listitem == jobname):
486                palmrunline = history[i-1]
487                palmrunline = palmrunline[17:]
488                palmrunline = palmrunline[:len(palmrunline)-1]
489                palmrunline = filter(None,palmrunline.split("("))[0]
490                self.groupBox.findChild(QtGui.QLineEdit,"commandline").setText(palmrunline)
491               
492             
493                tag = history[i-1].split('\n')[0]
494                tag = filter(None,tag.split("("))[1]
495                tag = tag.replace(")","")
496
497                self.groupBox.findChild(QtGui.QLineEdit,"line_tag").setText(tag)
498                self.setup_gui(palmrunline)
499                self.list_jobname.item(itemint).setSelected(True)   
500               
501                return
502            i = i-1
503               
504    # Change run identifer (initial, restart, coupled...)
505    ######################################################
506    def change_rc_list(self):
507        drop_job = self.group_execution.findChild(QtGui.QComboBox,"drop_job").currentText()   
508        self.change_commandline("a","")
509   
510        # Enable PE distribution for atmosphere/ocean
511        if ( drop_job == "Restart run (coupled atmosphere ocean)" or drop_job == "Initial run (coupled atmosphere ocean)"):
512            drop_atmos = self.group_coupled.findChild(QtGui.QLineEdit,"line_PE_atmos").text() 
513            drop_ocean = self.group_coupled.findChild(QtGui.QLineEdit,"line_PE_ocean").text() 
514            s = "%s %s" % (drop_atmos,drop_ocean)
515            self.change_commandline("Y",s)
516   
517   
518        if ( drop_job == "Restart run" or drop_job == "Restart run (coupled atmosphere ocean)"):
519           self.change_commandline("r","")
520
521        # Check of ocean runs
522        else:
523            self.delete_commandline("Y")
524            if (drop_job == "Precursor run (ocean)"):
525                self.activate_flag("y")
526            else:
527                self.deactivate_flag("y")
528           
529    # changes commandline depending on parameters
530    ##########################################################     
531    def change_commandline(self, id_str, fwt_str):
532        fwt_str = str(fwt_str) 
533        initialize = False
534        palmrunline = str(self.groupBox.findChild(QtGui.QLineEdit,"commandline").text())   
535        s = " -%s " % (id_str)
536        splitline = filter(None,palmrunline.split(s))
537
538        if ( len(splitline) == 0 ):
539                splitline.append("palmrun")
540                splitline.append(" ")
541                initialize = True
542
543        elif ( len(splitline) == 1 ):
544            splitline.append(" ")
545       
546        param = splitline[1].split("-")
547   
548        # Change in parameter "r" (jobname)
549        if (id_str == "r"):
550            filename = str(self.group_execution.findChild(QtGui.QLineEdit,"line_jobname").text())
551            s = filename.split("JOBS/") 
552            param[0] = s[len(s)-1]
553     
554            if ( initialize == True ):#and self.group_runcontrol.isEnabled() == True ):
555                self.group_execution.setEnabled(True)
556                self.group_execution.findChild(QtGui.QComboBox,"drop_job").setEnabled(True)
557                self.group_advanced.setEnabled(True)
558                self.groupBox.findChild(QtGui.QPushButton,"button_start").setEnabled(True) 
559                self.menuBar.findChild(QtGui.QMenu,"menuStart").actions()[3].setEnabled(True)
560                self.groupBox.findChild(QtGui.QLineEdit,"line_tag").setEnabled(True)
561           
562            elif ( param[0] == ""):           
563                self.group_execution.setEnabled(False)
564                self.group_execution.findChild(QtGui.QComboBox,"drop_job").setEnabled(False)
565                self.groupBox.findChild(QtGui.QPushButton,"button_start").setEnabled(False) 
566                self.menuBar.findChild(QtGui.QMenu,"menuStart").actions()[3].setEnabled(False)
567                self.group_advanced.setEnabled(False)
568                self.groupBox.findChild(QtGui.QLineEdit,"line_tag").setEnabled(True)
569                self.delete_commandline("r")
570                self.change_commandline("a","remove")
571                return 1 
572           
573            else:
574
575                self.group_execution.setEnabled(True)
576                self.drop_job.setEnabled(True)
577                self.group_advanced.setEnabled(True)
578                   
579        # Change in parameter "a" (run control list)
580        elif (id_str == "a"): 
581   
582            drop_job = self.group_execution.findChild(QtGui.QComboBox,"drop_job").currentText()
583            rc_flag = "#"
584   
585            if (drop_job == "Initial run"):
586                rc_flag = "#"
587           
588            elif (drop_job == "Restart run"):           
589                rc_flag = "r"
590           
591            elif (drop_job == "Precursor run (atmosphere)"):           
592                rc_flag = "#"
593           
594            elif (drop_job == "Precursor run (ocean)"):           
595                rc_flag = "o#"
596
597            elif (drop_job == "Initial run (coupled atmosphere ocean)"):           
598                rc_flag = "#"
599           
600            elif (drop_job == "Restart run (coupled atmosphere ocean)"):           
601                rc_flag = "r"
602           
603            param[0] = "\"d3%s" % (rc_flag)
604   
605   
606            if (drop_job == "Restart run (coupled atmosphere ocean)" or drop_job == "Initial run (coupled atmosphere ocean)"):
607                if (rc_flag == "#"):
608                   rc_flag = "o#"
609                else:
610                   rc_flag = "or"
611
612                param[0] = "%s d3%s" % (param[0],rc_flag)
613   
614            status_restarts = self.group_execution.findChild(QtGui.QCheckBox,"check_restarts").checkState()
615
616            if (status_restarts == 2):
617                param[0]="%s restart" % (param[0])
618
619
620            status_cycfill = self.group_execution.findChild(QtGui.QCheckBox,"check_cycfill").checkState()
621   
622            if (status_cycfill == 2):           
623                param[0]="%s fill" % (param[0])
624           
625            status_svf = self.group_execution.findChild(QtGui.QCheckBox,"check_svf").checkState()
626   
627            if (status_svf == 2):           
628                param[0]="%s svf" % (param[0])
629
630            param[0]="%s\"" % (param[0])
631 
632 
633            if ( fwt_str == "remove"):           
634                self.delete_commandline(id_str)
635                return 1
636           
637            else:           
638                self.button_start.setEnabled(True)
639                self.action_save.setEnabled(True)
640                self.groupBox.findChild(QtGui.QLineEdit,"line_tag").setEnabled(True)
641
642        # Change in any other parameter
643        else:
644            if ( fwt_str != ""):           
645                param[0] = "\"%s\"" % (fwt_str)
646           
647            else:           
648                self.delete_commandline(id_str)
649                return 1
650                       
651        # Join the new palmrunline
652        splitline[1]= " -".join(param)
653               
654               
655        s = " -%s " % (id_str)
656        newpalmrunline = s.join(splitline)
657   
658        # Pr the new palmrunline to mainwindow
659        newpalmrunline = newpalmrunline.replace("  "," ")
660        self.groupBox.findChild(QtGui.QLineEdit,"commandline").setText(newpalmrunline)
661
662    # change lineinput depending on sender
663    ###################################################################################
664    def change_lineinput(self):
665        if ( self.sender() == self.group_execution.findChild(QtGui.QComboBox, "combo_configuration") ):
666            tmptext = self.group_execution.findChild(QtGui.QComboBox, "combo_configuration").currentText()
667            if tmptext.isEmpty():
668               self.change_commandline("c"," ")
669               self.group_execution.findChild(QtGui.QPushButton,'button_palmbuild').setEnabled(False)
670            else:
671               self.change_commandline("c",tmptext)
672               self.group_execution.findChild(QtGui.QPushButton,'button_palmbuild').setEnabled(True)         
673
674        elif ( self.sender() == self.group_execution.findChild(QtGui.QLineEdit,"line_q")):
675            tmptext = self.group_execution.findChild(QtGui.QLineEdit,"line_q").text()
676            self.change_commandline("q",tmptext)
677       
678        elif ( self.sender() == self.group_execution.findChild(QtGui.QLineEdit,"line_account")):
679            tmptext = self.group_execution.findChild(QtGui.QLineEdit,"line_account").text()
680            self.change_commandline("A",tmptext)
681       
682        elif ( self.sender() ==  self.group_execution.findChild(QtGui.QLineEdit,"line_pe")):
683            tmptext = self.group_execution.findChild(QtGui.QLineEdit,"line_pe").text()
684            self.change_commandline("X",tmptext)
685       
686        elif ( self.sender() == self.group_execution.findChild(QtGui.QLineEdit,"line_tpn")):
687            tmptext = self.group_execution.findChild(QtGui.QLineEdit,"line_tpn").text()
688            self.change_commandline("T",tmptext)
689               
690        elif ( self.sender() == self.group_execution.findChild(QtGui.QLineEdit,"line_time")):
691            tmptext = self.group_execution.findChild(QtGui.QLineEdit,"line_time").text()
692            self.change_commandline("t",tmptext)
693       
694        elif ( self.sender() == self.group_advanced.findChild(QtGui.QLineEdit,"line_M")):
695            tmptext = self.group_advanced.findChild(QtGui.QLineEdit,"line_M").text()
696            self.change_commandline("M",tmptext)
697       
698        elif ( self.sender() == self.group_advanced.findChild(QtGui.QLineEdit,"line_m")):
699            tmptext = self.group_advanced.findChild(QtGui.QLineEdit,"line_m").text()
700            self.change_commandline("m",tmptext)
701       
702        elif ( self.sender() == self.group_advanced.findChild(QtGui.QLineEdit,"line_D")):
703            tmptext = self.group_advanced.findChild(QtGui.QLineEdit,"line_D").text()
704            self.change_commandline("D",tmptext)
705       
706        elif ( self.sender() == self.group_advanced.findChild(QtGui.QLineEdit,"line_c")):
707            tmptext = self.group_advanced.findChild(QtGui.QLineEdit,"line_c").text()
708            if ( tmptext == ".palmrungui.config"):
709                tmptext = ""
710            self.change_commandline("c",tmptext)
711       
712        elif ( self.sender() == self.group_advanced.findChild(QtGui.QLineEdit,"line_s")):
713            tmptext = self.group_advanced.findChild(QtGui.QLineEdit,"line_s").text()
714            self.change_commandline("s",tmptext)
715               
716        elif ( self.sender() == self.group_advanced.findChild(QtGui.QLineEdit,"line_w")):
717            tmptext = self.group_advanced.findChild(QtGui.QLineEdit,"line_w").text()
718            self.change_commandline("w",tmptext)
719       
720        elif ( self.sender() == self.group_coupled.findChild(QtGui.QLineEdit,"line_PE_atmos") or 
721               self.sender() == self.group_coupled.findChild(QtGui.QLineEdit,"line_PE_ocean")):
722            t1 = self.group_coupled.findChild(QtGui.QLineEdit,"line_PE_atmos").text()
723            t2 = self.group_coupled.findChild(QtGui.QLineEdit,"line_PE_ocean").text()           
724            tmptext = "%s %s" % (t1,t2)
725           
726            self.change_commandline("Y",tmptext)
727
728            # try catch sowas in der art
729            pe1 = 0
730            pe2 = 0
731           
732            try:
733                pe1 = int(t1)
734            except ValueError:           
735                pass
736               
737            try:
738                pe2 = int(t2)
739            except ValueError:
740                pass
741               
742            PE_total = pe1+pe2   
743            self.group_execution.findChild(QtGui.QLineEdit,"line_pe").setText(str(PE_total))
744            self.change_commandline("X",str(PE_total))
745         
746    # deletes parameter from commandline
747    #####################################################################################
748    def delete_commandline(self, id_str):   
749        # Read palmrunline
750        commandline = self.groupBox.findChild(QtGui.QLineEdit,"commandline")
751        palmrunline = str(commandline.text())
752        s = " -%s" % (id_str)
753        splitline = filter(None,palmrunline.split(s))
754       
755        if ( len(splitline) == 1):
756            return 1
757        else:
758            param = splitline[1].split("-")
759            param[0] = ""
760            splitline[1]= " -".join(param)
761            newpalmrunline = "".join(splitline)
762            newpalmrunline = newpalmrunline.replace("  "," ")
763   
764            # Print new palmrunline to screen
765            commandline.setText(newpalmrunline)
766       
767    # controls flags
768    ###################################################################################
769    def check_flags(self):
770        status = self.group_execution.findChild(QtGui.QCheckBox,"check_delete_tmp_files" ).checkState()
771        if (status == 2):     
772            self.activate_flag("B")
773        else:
774            self.deactivate_flag("B")
775   
776        status = self.group_execution.findChild(QtGui.QCheckBox,"check_verbose" ).checkState()
777        if (status == 2):
778            self.activate_flag("v") 
779        else:
780            self.deactivate_flag("v")
781       
782        status = self.group_advanced.findChild(QtGui.QCheckBox,"check_b" ).checkState() 
783        if (status == 2):
784            self.activate_flag("b")
785        else:
786            self.deactivate_flag("b")
787   
788        status = self.group_advanced.findChild(QtGui.QCheckBox,"check_F" ).checkState()   
789        if (status == 2):
790            self.activate_flag("F")
791        else:
792            self.deactivate_flag("F")
793           
794        status = self.group_advanced.findChild(QtGui.QCheckBox,"check_I" ).checkState() 
795        if (status == 2):
796            self.activate_flag("I")
797        else:
798            self.deactivate_flag("I")
799
800        status = self.group_advanced.findChild(QtGui.QCheckBox,"check_k" ).checkState() 
801        if (status == 2):
802            self.activate_flag("k")
803        else:
804            self.deactivate_flag("k")
805
806        status = self.group_advanced.findChild(QtGui.QCheckBox,"check_O" ).checkState() 
807        if (status == 2):
808            self.activate_flag("O")
809        else:
810            self.deactivate_flag("O")
811
812        status = self.group_advanced.findChild(QtGui.QCheckBox,"check_x" ).checkState() 
813        if (status == 2):
814            self.activate_flag("x")
815        else:
816            self.deactivate_flag("x")
817       
818        status = self.group_advanced.findChild(QtGui.QCheckBox,"check_Z" ).checkState() 
819        if (status == 2):
820            self.activate_flag("Z")
821        else:
822            self.deactivate_flag("Z")
823       
824    # changes flag to parameter
825    ##################################################################################   
826    def activate_flag(self, id_str):
827        commandline = self.groupBox.findChild(QtGui.QLineEdit,"commandline")
828        palmrunline = str(commandline.text())
829        s = " -%s" % (id_str)
830        splitline = filter(None,palmrunline.split(s))
831       
832        if ( len(splitline) == 1):
833            splitline.append("")
834            s = " -%s" % (id_str)
835            newpalmrunline = s.join(splitline)
836            newpalmrunline = newpalmrunline.replace("  "," ")
837            commandline.setText(newpalmrunline)               
838       
839    # deletes flag in commandline
840    ####################################################################################   
841    def deactivate_flag(self, id_str):
842        commandline = self.groupBox.findChild(QtGui.QLineEdit,"commandline")
843        palmrunline = str(commandline.text())
844        s = " -%s" % (id_str)
845        splitline = filter(None,palmrunline.split(s))
846 
847        newpalmrunline = "".join(splitline)
848        newpalmrunline = newpalmrunline.replace("  "," ")
849        commandline.setText(newpalmrunline)     
850
851    # Clears window
852    #################################################################################
853    def reset_window(self):
854        self.setupUi(self)
855        self.tabWidget.setCurrentIndex(0)
856        self.palm_logo.setPixmap(QtGui.QPixmap(palm_dir + "/trunk/SCRIPTS/palmrungui_files/logo.png"))   
857        self.recent_jobs(50)
858        self.load_jobs()
859       
860
861    # Safes current commandline and user parameters to default file
862    ################################################################################
863    def save_default(self):
864        user_string = self.group_advanced.findChild(QtGui.QLineEdit,"line_user").text()
865        cmd_string = self.groupBox.findChild(QtGui.QLineEdit,"commandline").text()
866       
867        string_to_file = cmd_string
868        if (user_string != ""): 
869            string_to_file = "%s%s" % (string_to_file,user_string)
870       
871        filename ="%s/.palmrungui.default" % (palm_dir)
872        tmstamp = strftime("%Y/%m/%d %H:%M")
873       
874        file = open(filename,"w")
875        s = "%s %s" % (tmstamp, string_to_file)
876        file.write(s)
877        file.close()       
878
879       
880    # Executes command which starts watchdog (start palm_wd)
881    ########################################################
882    def start_watchdog(self):
883        subprocess.Popen(["nohup","palm_wd",">>","/dev/null", "2>&1","&"])
884
885    # Opens "help" dialog
886    #################################
887    def help(self):       
888        dialog = HelpDialog()
889        dialog.exec_()
890
891    # Opens "about" dialog
892    ##################################
893    def about_gui(self):
894        dialog = AboutDialog()
895        dialog.exec_()
896
897    # commandline to buttons etc
898    ##############################
899    def setup_gui(self, palmrun_str): 
900     
901        #self.palm_logo.setPixmap(QtGui.QPixmap(palm_dir + "/trunk/SCRIPTS/palmrungui_files/logo.png"))   
902     
903        #  Some initial settings
904        user = "" 
905        coupled_run = False 
906        ocean_run   = False 
907        nojob       = False 
908
909        #Split parameters in palmrunline
910        splitline = palmrun_str.split(" -")
911       
912        if ( splitline[0] != "palmrun"):
913            return 1
914
915        else:
916            self.group_execution.setEnabled(True) 
917
918        # Loop for all parameters in palmrunline
919        i = len(splitline)-1
920        while i >= 1:
921
922            # Determine parameter
923            splitparameter = splitline[i].split(" ")
924
925            parameter = splitparameter[0] 
926            splitparameter.pop(0)
927            options = " ".join(splitparameter) 
928            options = options.replace("\"","") 
929
930            # Check for suitable switch
931            if ( parameter == "r"):
932             
933                if ( options != ""):
934                    self.group_execution.findChild(QtGui.QLineEdit,"line_jobname").setText(options) 
935                    nojob = False 
936               
937                else:                 
938                    nojob = True 
939               
940            elif ( parameter == "c"):
941                tmpindex = self.group_execution.findChild(QtGui.QComboBox, "combo_configuration").findText(options.strip(),QtCore.Qt.MatchExactly)
942                if tmpindex != -1: 
943                   self.group_execution.findChild(QtGui.QComboBox, "combo_configuration").setCurrentIndex(tmpindex)
944                else:
945                   self.group_execution.findChild(QtGui.QComboBox, "combo_configuration").setCurrentIndex(0)
946            elif ( parameter == "q"):
947                self.group_execution.findChild(QtGui.QLineEdit,"line_q").setText(options) 
948             
949            elif ( parameter == "A"):
950                self.group_execution.findChild(QtGui.QLineEdit,"line_account").setText(options) 
951             
952            elif ( parameter == "X"):
953                self.group_execution.findChild(QtGui.QLineEdit,"line_pe").setText(options) 
954             
955            elif ( parameter == "T"):
956                self.group_execution.findChild(QtGui.QLineEdit,"line_tpn").setText(options) 
957             
958            elif ( parameter == "t"):
959                self.group_execution.findChild(QtGui.QLineEdit,"line_time").setText(options) 
960             
961            elif ( parameter == "B"):
962                self.group_execution.findChild(QtGui.QCheckBox,"check_delete_tmp_files").setChecked(True) 
963             
964            elif ( parameter == "v"):
965                self.group_execution.findChild(QtGui.QCheckBox,"check_verbose").setChecked(True) 
966                         
967            elif ( parameter == "b"): 
968                self.group_advanced.findChild(QtGui.QCheckBox,"check_b").setChecked(True) 
969             
970            elif ( parameter == "F"):
971                self.group_advanced.findChild(QtGui.QCheckBox,"check_F").setChecked(True) 
972             
973            elif ( parameter == "I"):
974                self.group_advanced.findChild(QtGui.QCheckBox,"check_I").setChecked(True) 
975             
976            elif ( parameter == "k"):
977                self.group_advanced.findChild(QtGui.QCheckBox,"check_k").setChecked(True) 
978             
979            elif ( parameter == "O"): 
980                self.group_advanced.findChild(QtGui.QCheckBox,"check_O").setChecked(True) 
981             
982            elif ( parameter == "x"):             
983                self.group_advanced.findChild(QtGui.QCheckBox,"check_x").setChecked(True) 
984             
985            elif ( parameter == "Z"):
986                self.group_advanced.findChild(QtGui.QCheckBox,"check_Z").setChecked(True) 
987               
988            elif ( parameter == "m"):
989                self.group_advanced.findChild(QtGui.QLineEdit,"line_m").setText(options) 
990             
991            elif ( parameter == "M"):
992                self.group_advanced.findChild(QtGui.QLineEdit,"line_M").setText(options) 
993                         
994            elif ( parameter == "D"):
995                self.group_advanced.findChild(QtGui.QLineEdit,"line_D").setText(options) 
996             
997            elif ( parameter == "c"):
998                self.group_advanced.findChild(QtGui.QLineEdit,"line_c").setText(options) 
999                         
1000            elif ( parameter == "s"):
1001                self.group_advanced.findChild(QtGui.QLineEdit,"line_s").setText(options) 
1002             
1003            elif ( parameter == "w"):
1004                self.group_advanced.findChild(QtGui.QLineEdit,"line_w").setText(options) 
1005             
1006
1007            # Determine settings for coupled restart runs
1008            elif ( parameter == "Y"):
1009                optionssplit = options.split(" ") 
1010               
1011                group_coupled = self.group_execution.findChild(QtGui.QGroupBox,"group_coupled")
1012                group_coupled.findChild(QtGui.QLineEdit,"line_PE_atmos").setEnabled(True) 
1013                group_coupled.findChild(QtGui.QLineEdit,"line_PE_ocean").setEnabled(True) 
1014                group_coupled.findChild(QtGui.QLabel,"label_coupled1").setEnabled(True) 
1015                group_coupled.findChild(QtGui.QLabel,"label_coupled2").setEnabled(True) 
1016                group_coupled.findChild(QtGui.QLabel,"label_coupled3").setEnabled(True) 
1017                group_coupled.findChild(QtGui.QLabel,"label_coupling").setEnabled(True) 
1018
1019                if (optionssplit.count() == 2):
1020                    group_coupled.findChild(QtGui.QLineEdit,"line_PE_atmos").setEnabled(optionssplit[0]) 
1021                    group_coupled.findChild(QtGui.QLineEdit,"line_PE_ocean").setEnabled(optionssplit[1])
1022                 
1023                else:                 
1024                    group_coupled.findChild(QtGui.QLineEdit,"line_PE_atmos").setText("") 
1025                    group_coupled.findChild(QtGui.QLineEdit,"line_PE_ocean").setText("") 
1026 
1027                 
1028                coupled_run = True 
1029           
1030            elif ( parameter == "y"):             
1031                self.group_execution.findChild(QtGui.QComboBox, "drop_job").setCurrentIndex(3) 
1032             
1033
1034            # Determine settings for the run control list
1035            elif ( parameter == "a"):
1036             
1037                optionssplit = options.split(" ") 
1038
1039                options_2 = None
1040                options_all = None
1041               
1042                j = 0
1043                while j < len(optionssplit):
1044                 
1045                    options_all = optionssplit[j] 
1046                    options_2 = optionssplit[j][:2] 
1047                                             
1048                    if (options_2 == "d3"):     
1049                        if (options_all[:3][-1] == "#"):
1050                            self.group_execution.findChild(QtGui.QComboBox, "drop_job").setCurrentIndex(0) 
1051                        elif (options_all[:3][-1] == "r"):
1052                            self.group_execution.findChild(QtGui.QComboBox, "drop_job").setCurrentIndex(1) 
1053                       
1054                        elif (options_all[:3][-1] == "o"):
1055                            ocean_run = True 
1056                       
1057                    if (options_all == "restart"):
1058                        self.group_execution.findChild(QtGui.QCheckBox,"check_restarts").setChecked(True) 
1059
1060                    j = j+1
1061
1062            # All unknown parameters are set as extra user parameters
1063            else: 
1064                print parameter
1065                user = "%s-%s \"%s\" " % (user,parameter,options)
1066                splitline.removeAt(i) 
1067
1068            i = i-1
1069        # Change drop box state in case of ocean precursor or coupled restart runs
1070        if ( ocean_run == True ):
1071            if ( coupled_run == True ):
1072                self.group_execution.findChild(QtGui.QComboBox, "drop_job").setCurrentIndex(4) 
1073           
1074            else:
1075                self.group_execution.findChild(QtGui.QComboBox, "drop_job").setCurrentIndex(3) 
1076
1077        if ( user != ""):
1078            self.group_advanced.findChild(QtGui.QLineEdit,"line_user").setText(user)
1079
1080        # Join palmrunline and post it to mainwindow
1081        palmrunline = " -".join(splitline) 
1082        self.groupBox.findChild(QtGui.QLineEdit,"commandline").setText(palmrunline)         
1083
1084        # Disable mainwindow if no job was found, otherwise enable
1085        if ( nojob == True ):
1086            self.group_execution.setEnabled(False) 
1087            self.groupBox.findChild(QtGui.QPushButton,"button_start").setEnabled(False) 
1088            self.menuBar.findChild(QtGui.QMenu,"menuStart").actions()[3].setEnabled(False) 
1089            self.group_execution.findChild(QtGui.QComboBox, "drop_job").setEnabled(False) 
1090            self.group_advanced.setEnabled(False) 
1091            self.check_advanced.setEnabled(False) 
1092            self.groupBox.findChild(QtGui.QLineEdit,"line_tag").setEnabled(False)
1093         
1094        else:
1095            self.group_execution.setEnabled(True) 
1096            self.groupBox.findChild(QtGui.QPushButton,"button_start").setEnabled(True) 
1097            self.menuBar.findChild(QtGui.QMenu,"menuStart").actions()[3].setEnabled(True)
1098            self.group_execution.findChild(QtGui.QComboBox, "drop_job").setEnabled(True) 
1099            self.group_advanced.setEnabled(True) 
1100            self.groupBox.findChild(QtGui.QLineEdit,"line_tag").setEnabled(True)
1101
1102
1103        self.tabWidget.setCurrentIndex(0)
1104
1105
1106    ## Open from history
1107    ###################################
1108    def open_from_file(self):
1109
1110#      Show History
1111       opt = OpenHistoryBox()
1112       opt.exec_()
1113
1114       palmrunline = str(history_entry)
1115       palmrunline = palmrunline[17:]
1116       palmrunline = palmrunline[:len(palmrunline)-1]
1117       palmrunline = filter(None,palmrunline.split("("))[0]
1118       self.groupBox.findChild(QtGui.QLineEdit,"commandline").setText(palmrunline)
1119
1120#      Set selected item to jobname in "available jobs" list
1121       jobname = str(history_entry[17:])
1122       jobname = filter(None,jobname.split(" -r"))[1]
1123       jobname = jobname.strip()
1124       jobname = filter(None,jobname.split(" "))[0]
1125       jobname = jobname.replace("\"","") 
1126       item2int = self.list_jobs.findItems(jobname,QtCore.Qt.MatchCaseSensitive)
1127
1128       if ( item2int != [] ):
1129          self.list_jobs.setCurrentItem(item2int[0])
1130          self.update_input()
1131
1132#      Add tooltip tag
1133       tag = str(history_entry).split('\n')[0]
1134       tag = filter(None,tag.split("("))[1]
1135       tag = tag.replace(")","")
1136       self.groupBox.findChild(QtGui.QLineEdit,"line_tag").setText(tag)
1137 
1138#      Process palmrungui to set up gui controls
1139       self.setup_gui(palmrunline)
1140
1141
1142    def update_all(self):
1143 
1144       self.setEnabled(False)
1145       self.list_input.clear() 
1146       self.list_user.clear()
1147       self.list_monitoring.clear()
1148       self.list_output.clear()
1149       self.load_jobs()
1150       self.setEnabled(True)
1151       self.update_input()
1152
1153
1154    # Load jobs into list
1155    def load_jobs(self):
1156       
1157       selected_job = self.list_jobs.currentItem()
1158       
1159       if ( selected_job is not None ):
1160          jobname = selected_job.text()
1161       else:
1162          jobname = ""
1163
1164       self.list_jobs.clear() 
1165       self.line_path.setText(job_dir + "/")
1166       
1167       list_of_files = os.listdir(job_dir)
1168     
1169
1170       for i in range(0,len(list_of_files)):
1171          tmp_file = job_dir + "/" + list_of_files[i]
1172
1173          if ( os.path.isdir(tmp_file) ):
1174             self.list_jobs.addItem(str(list_of_files[i]))
1175       
1176
1177
1178       item2int = self.list_jobs.findItems(jobname,QtCore.Qt.MatchCaseSensitive)
1179       
1180       if ( item2int != [] ):
1181          self.list_jobs.setCurrentItem(item2int[0])
1182
1183
1184    # Update input and user code lists
1185    def update_input(self):
1186
1187       self.labeltimer.stop() 
1188
1189     
1190       self.list_input.clear() 
1191       self.list_user.clear()
1192       self.list_monitoring.clear()
1193       self.list_output.clear()
1194       
1195       jobitem = self.list_jobs.currentItem()
1196       
1197       if ( jobitem != None ):
1198       
1199          job_to_show = job_dir + "/" + jobitem.text() + "/INPUT"
1200
1201          if ( os.path.isdir(job_to_show) ):
1202
1203             list_of_files = os.listdir(job_to_show)
1204         
1205             for i in range(0,len(list_of_files)):
1206                tmp_file = job_to_show + "/" + list_of_files[i]
1207             
1208                if ( os.path.isfile(tmp_file) ):
1209                   self.list_input.addItem(str(list_of_files[i]) + " (" + file_size(tmp_file) + ")")
1210 
1211          job_to_show = job_dir + "/" + jobitem.text() + "/USER_CODE"
1212       
1213          if ( os.path.isdir(job_to_show) ):
1214         
1215             list_of_files = os.listdir(job_to_show)
1216         
1217             for i in range(0,len(list_of_files)):
1218                tmp_file = job_to_show + "/" + list_of_files[i]
1219
1220                if ( os.path.isfile(tmp_file) ):
1221                   self.list_user.addItem(str(list_of_files[i]))
1222
1223          job_to_show = job_dir + "/" + jobitem.text() + "/MONITORING"
1224       
1225          if ( os.path.isdir(job_to_show) ):
1226         
1227             list_of_files = os.listdir(job_to_show)
1228         
1229             for i in range(0,len(list_of_files)):
1230                tmp_file = job_to_show + "/" + list_of_files[i]
1231
1232                if ( os.path.isfile(tmp_file) ):
1233                   self.list_monitoring.addItem(str(list_of_files[i]) + " (" + file_size(tmp_file) + ")")
1234
1235          job_to_show = job_dir + "/" + jobitem.text() + "/OUTPUT"
1236
1237          if ( os.path.isdir(job_to_show) ):
1238
1239             list_of_files = os.listdir(job_to_show)
1240
1241             for i in range(0,len(list_of_files)):
1242                tmp_file = job_to_show + "/" + list_of_files[i]
1243
1244                if ( os.path.isfile(tmp_file) ):
1245                   self.list_output.addItem(str(list_of_files[i]) + " (" + file_size(tmp_file) + ")")
1246 
1247          self.group_execution.findChild(QtGui.QLineEdit,"line_jobname").setText(jobitem.text())
1248       self.group_history.findChild(QtGui.QListWidget,"list_jobname").clearSelection()
1249
1250       self.timetimer.start()
1251       self.timer.start(update_frequency)
1252       self.labeltimer.start(update_frequency/10)
1253       self.push_update.setText("Update (" + str(int(update_frequency/1000/60)) + " min)")
1254       QtGui.QApplication.processEvents()
1255
1256       # Change palmrunline accordingly
1257       self.change_commandline("r","")
1258       self.change_commandline("a","") 
1259
1260    # Make a copy of a job
1261    def copy_job(self):
1262 
1263       self.setEnabled(False)
1264       old_job_name = self.list_jobs.currentItem().text()
1265       
1266       text, ret = QtGui.QInputDialog.getText(self, "Copy job", "Enter new job name:", mode = QtGui.QLineEdit.Normal, text = old_job_name)
1267       
1268       if ( ret ):
1269          new_job_name = str(text)
1270       else:
1271           self.setEnabled(True)
1272           return
1273         
1274       new_input_dir  = job_dir + "/" + new_job_name + "/INPUT"
1275
1276#      check if a job exists with the new job name 
1277       if ( os.path.isdir(new_input_dir) ):
1278           notify = QtGui.QMessageBox.warning(self,'Create new job directory',"Error. Could not create job directory. A job with the new name already exists.")
1279           self.setEnabled(True)
1280           return
1281       else:
1282           os.makedirs(new_input_dir)
1283
1284#      copy and rename input files (if present)       
1285       job_to_copy = job_dir + "/" + old_job_name + "/INPUT"
1286
1287       if ( os.path.isdir(job_to_copy) ):
1288
1289          list_of_files = os.listdir(job_to_copy)
1290         
1291          for i in range(0,len(list_of_files)):
1292
1293             tmp_file = job_to_copy + "/" + list_of_files[i]         
1294             new_file = new_input_dir + "/" + list_of_files[i].replace(old_job_name, new_job_name)
1295             shutil.copy(tmp_file, new_file)
1296
1297
1298
1299
1300       new_user_dir  = job_dir + "/" + new_job_name + "/USER_CODE"
1301       
1302#      check if user code exists in the new job directory
1303       if ( os.path.isdir(new_user_dir) ):
1304           notify = QtGui.QMessageBox.warning(self,'Create new user code directory',"Error. Could not create user code directory. A user code directiory with the new name already exists.")
1305           self.setEnabled(True)
1306           return
1307       else:
1308           os.makedirs(new_user_dir)
1309
1310
1311#      copy user code files (if present)       
1312       user_to_copy = job_dir + "/" + old_job_name + "/USER_CODE"
1313
1314       if ( os.path.isdir(user_to_copy) ):
1315
1316          list_of_files = os.listdir(user_to_copy)
1317         
1318          for i in range(0,len(list_of_files)):
1319
1320             tmp_file = user_to_copy + "/" + list_of_files[i]         
1321             new_file = new_user_dir + "/" + list_of_files[i]
1322             shutil.copy(tmp_file, new_file)
1323
1324       self.load_jobs()
1325       self.list_input.clear() 
1326       self.list_user.clear()
1327       self.list_monitoring.clear()
1328       self.list_output.clear()
1329       self.setEnabled(True)
1330
1331
1332    # Create a whole set of jobs
1333    def create_set(self):
1334 
1335       global set_list
1336#      disable mainwindow 
1337       self.setEnabled(False)
1338     
1339#      show Options Dialog     
1340       opt = CreateSetBox()
1341       opt.exec_()
1342
1343       old_job_name = self.list_jobs.currentItem().text()
1344
1345       for j in range(0,len(set_list)):
1346
1347          if ( set_list[j] != "" ):
1348             new_job_name   = str(set_list[j])
1349             new_input_dir  = job_dir + "/" + str(set_list[j]) + "/INPUT"
1350          else:
1351             continue
1352
1353#         check if a job exists with the new job name 
1354          if ( os.path.isdir(new_input_dir) ):
1355             notify = QtGui.QMessageBox.warning(self,'Create new job directory',"Error. Could not create job directory. A job with the new name already exists.")
1356             self.setEnabled(True)
1357             return
1358          else:
1359             os.makedirs(new_input_dir)
1360
1361#         copy and rename input files (if present)       
1362          job_to_copy = job_dir + "/" + old_job_name + "/INPUT"
1363
1364          if ( os.path.isdir(job_to_copy) ):
1365
1366             list_of_files = os.listdir(job_to_copy)
1367         
1368             for i in range(0,len(list_of_files)):
1369
1370                tmp_file = job_to_copy + "/" + list_of_files[i]         
1371                new_file = new_input_dir + "/" + list_of_files[i].replace(old_job_name, new_job_name)
1372                shutil.copy(tmp_file, new_file)
1373
1374
1375          new_user_dir  = job_dir + "/" + new_job_name + "/USER_CODE"
1376       
1377#         check if user code exists in the new job directory
1378          if ( os.path.isdir(new_user_dir) ):
1379              notify = QtGui.QMessageBox.warning(self,'Create new user code directory',"Error. Could not create user code directory. A user code directiory with the new name already exists.")
1380              self.setEnabled(True)
1381              return
1382          else:
1383              os.makedirs(new_user_dir)
1384
1385
1386#         copy user code files (if present)       
1387          user_to_copy = job_dir + "/" + old_job_name + "/USER_CODE"
1388
1389          if ( os.path.isdir(user_to_copy) ):
1390
1391             list_of_files = os.listdir(user_to_copy)
1392         
1393             for i in range(0,len(list_of_files)):
1394
1395                tmp_file = user_to_copy + "/" + list_of_files[i]         
1396                new_file = new_user_dir + "/" + list_of_files[i]
1397                shutil.copy(tmp_file, new_file)
1398
1399          self.load_jobs()
1400          self.list_input.clear() 
1401          self.list_user.clear()
1402          self.list_monitoring.clear()
1403          self.list_output.clear()
1404
1405       self.setEnabled(True) 
1406       set_list = []
1407
1408
1409 # Add a custom context menu for the job selection list
1410    def openmenujob(self, position):
1411
1412        menu = QtGui.QMenu()
1413
1414        selection = self.list_jobs.selectedItems()
1415
1416        if ( len(selection) != 0 ):
1417
1418           copyAction = QtGui.QAction('Copy job', self)
1419           copyAction.triggered.connect(self.copy_job)
1420           createAction = QtGui.QAction('Create set from job', self)
1421           createAction.triggered.connect(self.create_set)
1422           delAction = QtGui.QAction('Delete job', self)
1423           delAction.triggered.connect(self.DeleteJob)
1424
1425           menu.addAction(copyAction)
1426           menu.addAction(createAction)
1427           menu.addAction(delAction)
1428
1429           action = menu.exec_(self.list_jobs.mapToGlobal(position))
1430       
1431       
1432 # Add a custom context menu
1433    def openmenuinput(self, position):
1434
1435        menu = QtGui.QMenu()
1436
1437        selection = self.list_input.selectedItems()
1438       
1439        if ( len(selection) != 0 ):
1440
1441
1442           openAction = QtGui.QAction('Open file(s)', self)
1443           openAction.setStatusTip('Open file(s) in your favorite editor')
1444           openAction.triggered.connect(self.OpenFilesInput)
1445
1446
1447           delAction = QtGui.QAction('Delete file(s)', self)
1448           delAction.triggered.connect(self.DeleteFilesInput)
1449
1450           menu.addAction(openAction)
1451           menu.addAction(delAction)
1452
1453           action = menu.exec_(self.list_input.mapToGlobal(position))
1454
1455 # Add a custom context menu
1456    def openmenuuser(self, position):
1457
1458        menu = QtGui.QMenu()
1459
1460        selection = self.list_user.selectedItems()
1461       
1462        if ( len(selection) != 0 ):
1463
1464           openAction = QtGui.QAction('Open file(s)', self)
1465           openAction.setStatusTip('Open file(s) in your favorite editor')
1466           openAction.triggered.connect(self.OpenFilesUser)
1467
1468
1469           delAction = QtGui.QAction('Delete file(s)', self)
1470           delAction.triggered.connect(self.DeleteFilesUser)
1471
1472           menu.addAction(openAction)
1473           menu.addAction(delAction)
1474           action = menu.exec_(self.list_user.mapToGlobal(position))
1475
1476 # Add a custom context menu
1477    def openmenuoutput(self, position):
1478
1479        menu = QtGui.QMenu()
1480
1481        selection = self.list_output.selectedItems()
1482       
1483        if ( len(selection) != 0 ):
1484
1485           openAction = QtGui.QAction('Open file(s)', self)
1486           openAction.setStatusTip('Open file(s) in your favorite editor')
1487           openAction.triggered.connect(self.OpenFilesOutput)
1488
1489
1490           delAction = QtGui.QAction('Delete file(s)', self)
1491           delAction.triggered.connect(self.DeleteFilesOutput)
1492
1493           menu.addAction(openAction)
1494           menu.addAction(delAction)
1495           action = menu.exec_(self.list_output.mapToGlobal(position))
1496
1497 # Add a custom context menu
1498    def openmenumonitoring(self, position):
1499
1500        menu = QtGui.QMenu()
1501
1502        selection = self.list_monitoring.selectedItems()
1503       
1504        if ( len(selection) != 0 ):
1505
1506           openAction = QtGui.QAction('Open file(s)', self)
1507           openAction.setStatusTip('Open file(s) in your favorite editor')
1508           openAction.triggered.connect(self.OpenFilesMonitoring)
1509
1510
1511           delAction = QtGui.QAction('Delete file(s)', self)
1512           delAction.triggered.connect(self.DeleteFilesMonitoring)
1513
1514           menu.addAction(openAction)
1515           menu.addAction(delAction)
1516           action = menu.exec_(self.list_monitoring.mapToGlobal(position))
1517
1518    def OpenConfig(self):
1519
1520       config = str(self.group_execution.findChild(QtGui.QComboBox, "combo_configuration").currentText())
1521       if ( config != "" ):
1522          filename = ".palm.config." + config
1523          open_file = "xdg-open " + filename
1524          os.system(str(open_file))
1525
1526    def OpenFilesInput(self):
1527   
1528       sel_job = self.list_jobs.currentItem().text()
1529       sel_files = self.list_input.selectedItems()
1530       
1531       input_dir = job_dir + "/" + sel_job + "/INPUT/"
1532       
1533       open_files = ""
1534       for i in range(0,len(sel_files)):
1535          open_files = open_files + "xdg-open " + input_dir +  sel_files[i].text().split("(")[0] + "; "
1536
1537       os.system(str(open_files))
1538
1539    def OpenFilesUser(self):
1540   
1541       sel_job = self.list_jobs.currentItem().text()
1542       sel_files = self.list_user.selectedItems()
1543       
1544       input_dir = job_dir + "/" + sel_job + "/USER_CODE/"
1545       
1546       open_files = ""
1547       for i in range(0,len(sel_files)):
1548          open_files = open_files + "xdg-open " + input_dir +  sel_files[i].text() + "; "
1549
1550       os.system(str(open_files)) 
1551       selection = self.list_jobs.selectedItems()
1552 
1553    def OpenFilesMonitoring(self):
1554   
1555       sel_job = self.list_jobs.currentItem().text()
1556       sel_files = self.list_monitoring.selectedItems()
1557       
1558       input_dir = job_dir + "/" + sel_job + "/MONITORING/"
1559       
1560       open_files = ""
1561       for i in range(0,len(sel_files)):
1562          open_files = open_files + "xdg-open " + input_dir +  sel_files[i].text().split("(")[0]  + "; "
1563
1564       os.system(str(open_files)) 
1565       selection = self.list_jobs.selectedItems()
1566 
1567    def OpenFilesOutput(self):
1568   
1569       sel_job = self.list_jobs.currentItem().text()
1570       sel_files = self.list_output.selectedItems()
1571       
1572       input_dir = job_dir + "/" + sel_job + "/OUTPUT/"
1573       
1574       open_files = ""
1575       for i in range(0,len(sel_files)):
1576          open_files = open_files + "xdg-open " + input_dir +  sel_files[i].text().split("(")[0] + "; "
1577
1578       os.system(str(open_files)) 
1579       selection = self.list_jobs.selectedItems()
1580
1581    def DeleteFilesInput(self):
1582
1583       status = QtGui.QMessageBox.question(self,'Delete Confirmation', "Are you sure you want to delete these files?", QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
1584
1585       if status == QtGui.QMessageBox.Yes:
1586
1587          sel_job = self.list_jobs.currentItem().text()
1588          sel_files = self.list_input.selectedItems()
1589
1590          input_dir = job_dir + "/" + sel_job + "/INPUT/"
1591
1592          for i in range(0,len(sel_files)):
1593             filename = input_dir +  sel_files[i].text().split("(")[0].trimmed()
1594             os.remove(filename)
1595
1596          self.update_all()
1597
1598
1599    def DeleteFilesUser(self):
1600
1601       status = QtGui.QMessageBox.question(self,'Delete Confirmation', "Are you sure you want to delete these files?", QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
1602
1603       if status == QtGui.QMessageBox.Yes:
1604
1605          sel_job = self.list_jobs.currentItem().text()
1606          sel_files = self.list_user.selectedItems()
1607
1608          input_dir = job_dir + "/" + sel_job + "/USER/"
1609
1610          for i in range(0,len(sel_files)):
1611             filename = input_dir +  sel_files[i].text().split("(")[0].trimmed()
1612             os.remove(filename)
1613
1614          self.update_all()
1615
1616
1617    def DeleteFilesMonitoring(self):
1618
1619       status = QtGui.QMessageBox.question(self,'Delete Confirmation', "Are you sure you want to delete these files?", QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
1620
1621       if status == QtGui.QMessageBox.Yes:
1622
1623          sel_job = self.list_jobs.currentItem().text()
1624          sel_files = self.list_monitoring.selectedItems()
1625
1626          input_dir = job_dir + "/" + sel_job + "/MONITORING/"
1627
1628          for i in range(0,len(sel_files)):
1629             filename = input_dir +  sel_files[i].text().split("(")[0].trimmed()
1630             os.remove(filename)
1631
1632          self.update_all()
1633
1634
1635    def DeleteFilesOutput(self):
1636
1637       status = QtGui.QMessageBox.question(self,'Delete Confirmation', "Are you sure you want to delete these files?", QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
1638
1639       if status == QtGui.QMessageBox.Yes:
1640
1641          sel_job = self.list_jobs.currentItem().text()
1642          sel_files = self.list_output.selectedItems()
1643
1644          input_dir = job_dir + "/" + sel_job + "/OUTPUT/"
1645
1646          for i in range(0,len(sel_files)):
1647             filename = input_dir +  sel_files[i].text().split("(")[0].trimmed()
1648             os.remove(filename)
1649
1650          self.update_all()
1651
1652    def DeleteJob(self):
1653
1654       status = QtGui.QMessageBox.question(self,'Delete Confirmation', "Are you sure you want to delete this job?", QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
1655
1656       if status == QtGui.QMessageBox.Yes:
1657
1658          sel_job = self.list_jobs.currentItem().text()
1659
1660          input_dir = job_dir + "/" + sel_job
1661          shutil.rmtree(str(input_dir))
1662
1663          self.update_all()
1664
1665# Message box for showing RUN_CONTROL output
1666class CreateSetBox(QtGui.QDialog):
1667    def __init__(self):
1668
1669        super(CreateSetBox, self).__init__()
1670
1671        uic.loadUi(palm_bin + '/palmrungui_files/create_set.ui', self)
1672
1673        self.show()
1674
1675        return
1676
1677#   Cancel button
1678    def rejected(self):
1679
1680       self.close()
1681
1682       return
1683
1684#   OK button
1685    def accept(self):
1686
1687       global set_list
1688
1689       text = self.list.toPlainText() 
1690       set_list = text.split('\n')
1691       self.close()
1692
1693       return
1694
1695# Message box for showing RUN_CONTROL output
1696class OpenHistoryBox(QtGui.QDialog):
1697    def __init__(self):
1698
1699        super(OpenHistoryBox, self).__init__()
1700
1701        uic.loadUi(palm_bin + '/palmrungui_files/history.ui', self)
1702
1703        if os.path.exists(palm_dir + "/.palmrungui.history"):
1704            pass
1705        else:
1706            return
1707
1708        filename = open(palm_dir + "/.palmrungui.history","r")
1709        history = filename.readlines()
1710        filename.close()
1711
1712
1713        list_jobname = self.findChild(QtGui.QListWidget,"list_history")
1714
1715        # Read history entries and append to recent job list
1716        len_history=len(history)-1
1717        i = 0
1718        while i<=len_history:
1719            list_jobname.addItem(history[i])
1720            i = i + 1
1721
1722        self.show()
1723
1724        return
1725
1726#   Select item / activate Load button
1727    def ItemSelected(self):
1728
1729       self.push_open.setEnabled(True)
1730
1731       return
1732
1733
1734#   Load job from history
1735    def OpenFromHistory(self):
1736
1737       global history_entry
1738       history_entry = self.list_history.selectedItems()[0].text()
1739
1740       self.close()
1741
1742       return
1743
1744#   Close history window
1745    def DiscardHistory(self):
1746
1747
1748       self.close()
1749
1750       return
1751
1752#   Clear history
1753    def ClearHistory(self):
1754
1755       status = QtGui.QMessageBox.question(self,'Delete Confirmation', "Are you sure you want to delete your history?", QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
1756
1757       if status == QtGui.QMessageBox.Yes:
1758
1759          if os.path.exists(palm_dir + "/.palmrungui.history"):
1760             os.remove(palm_dir + "/.palmrungui.history")
1761
1762
1763       return
1764
1765if __name__ == "__main__":
1766    app = QtGui.QApplication(sys.argv)
1767    window = Mainwindow()
1768    window.show()
1769    sys.exit(app.exec_())
Note: See TracBrowser for help on using the repository browser.