Beispiel #1
0
def main():
    start_gtk_thread()

    # Create a proper file:// URL pointing to demo.xhtml:
    file = os.path.abspath('demo.xhtml')
    uri = 'file://' + urllib.pathname2url(file)
    browser, web_recv, web_send = \
        synchronous_gtk_message(launch_browser)(uri,
                                                quit_function=Global.set_quit)

    # Finally, here is our personalized main loop, 100% friendly
    # with "select" (although I am not using select here)!:
    last_second = time.time()
    uptime_seconds = 1
    clicks = 0
    while not Global.quit:

        current_time = time.time()
        again = False
        msg = web_recv()
        if msg:
            msg = from_json(msg)
            again = True

        if msg == "got-a-click":
            clicks += 1
            web_send('document.getElementById("messages").innerHTML = %s' %
                     to_json('%d clicks so far' % clicks))
            # If you are using jQuery, you can do this instead:
            # web_send('$("#messages").text(%s)' %
            #          to_json('%d clicks so far' % clicks))

        if current_time - last_second >= 1.0:
            web_send('document.getElementById("uptime-value").innerHTML = %s' %
                     to_json('%d' % uptime_seconds))
            # If you are using jQuery, you can do this instead:
            # web_send('$("#uptime-value").text(%s)'
            #        % to_json('%d' % uptime_seconds))
            uptime_seconds += 1
            last_second += 1.0


        if again: pass
        else:     time.sleep(0.1)
Beispiel #2
0
def main():
    viki_config = VikiConfig()
    available_mods = scan.getAvailableModules(viki_config)

    start_gtk_thread()
    corePID = 0

    # Create a proper file:// URL pointing to demo.xhtml:
    file = os.path.abspath('core/gui/VIKI_main.html')
    uri = 'file://' + urllib.pathname2url(file)
    browser, web_recv, web_send = \
        synchronous_gtk_message(launch_browser)(uri,
                                                quit_function=Global.set_quit)

    # Predefine functions that react on buttons in GUI
    def vikiConnCheck():
        web_send('updateStatus("Communication okay")')

    def vikiRefreshModules():
        web_send('updateModules(%s)' %
                 helpers.toJSON(available_mods))

    def vikiStartRosCore():
        # sp = subprocess.Popen('/opt/ros/indigo/bin/roscore')
        sp = subprocess.Popen(['gnome-terminal', '-x', "{}/bin/roscore".format(viki_config.get_option('ros_dir'))])
        main.corePID = sp.pid # This PID is not the right one!
        web_send('enableStopCore()')
        web_send('updateStatus("ROS core started (PID: '+str(main.corePID)+')")')

    def vikiStopRosCore():
        # if main.corePID > 0: 
        #     os.kill(main.corePID, signal.SIGKILL)
        web_send('enableStartCore()')

    def vikiConfigXML(configXML):
        filename = 'configuration.xml'
        f = open(filename, 'w')
        f.write('<configurations>')
        f.write(configXML)
        f.write('</configurations>')
        f.close()

    def vikiConfigLaunch():
        configfromfile = config_interpreter.getConfig(config_id_to_use="VIKI-imported-config")     
        config_matcher.matchConfig(configfromfile, available_mods)
        writeLaunch.write(configfromfile)
        web_send('updateStatus("Written launch file")');

    def vikiRun():
        try:
            # run in new gnome terminal
            # don't know if this works with intellijIDEA, find out yourself if you use it.
            global ros_master_hostname
            env = "http://"+ros_master_hostname+":11311"
            pid = subprocess.Popen(args=["gnome-terminal", "-e", "./viki_launch.sh roslaunch aeroworks.launch"], env=dict(os.environ, **{"ROS_MASTER_URI":env})).pid
        except OSError:
            web_send('updateStatus("OSError")')
        web_send('updateStatus("Requested launch of AeroWorks.launch")')

    def vikiSetMasterUri(master_hostname):
        global ros_master_hostname
        ros_master_hostname= master_hostname
        web_send('updateStatus("Updated ROS_MASTER_URI to '+ros_master_hostname+'")')

    def vikiMakeAndRun(configXML):
        vikiConfigXML(configXML)
        vikiConfigLaunch()
        vikiRun()

    def vikiMakeNoRun(configXML):
        vikiConfigXML(configXML)
        vikiConfigLaunch()

    def vikiShowLaunch():
        web_send('updateStatus("Opening generated launch file...")')
        subprocess.Popen(args=["xdg-open", "aeroworks.launch"])

    def vikiShowConfig():
        web_send('updateStatus("Opening generated config file...")')
        subprocess.Popen(args=["xdg-open", "configuration.xml"])

    def vikiOpenRqtGraph():
        subprocess.Popen(["gnome-terminal", '-e', "./viki_launch.sh rqt_graph"])

    def add_filters(dialog):
        filter_text = gtk.FileFilter()
        filter_text.set_name("Text files")
        filter_text.add_mime_type("text/plain")
        dialog.add_filter(filter_text)

        filter_any = gtk.FileFilter()
        filter_any.set_name("Any files")
        filter_any.add_pattern("*")
        dialog.add_filter(filter_any)

    def vikiSave(project):
        dialog = gtk.FileChooserDialog("Please enter a file name",None,
                                       gtk.FILE_CHOOSER_ACTION_SAVE,
                                       (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                                        gtk.STOCK_SAVE, gtk.RESPONSE_OK))

        #add_filters(dialog)

        gtk.gdk.threads_enter()
        response = dialog.run()
        if response == gtk.RESPONSE_OK:
            f = open(dialog.get_filename(), mode='w+')
            f.write(project)
            web_send('updateStatus("Save finished")')
        elif response == gtk.RESPONSE_CANCEL:
            web_send('updateStatus("Save cancelled")')
        dialog.destroy()
        gtk.gdk.threads_leave()

    def vikiOpen():
        dialog = gtk.FileChooserDialog("Please choose a file",None,
                                       gtk.FILE_CHOOSER_ACTION_OPEN,
                                       (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                                        gtk.STOCK_OPEN, gtk.RESPONSE_OK))

        #add_filters(dialog)

        gtk.gdk.threads_enter()
        response = dialog.run()
        if response == gtk.RESPONSE_OK:
            f = open(dialog.get_filename(), mode='r')
            web_send('openFromJSON('+f.read()+')')
            web_send('updateStatus("Open finished")')
        elif response == gtk.RESPONSE_CANCEL:
            web_send('updateStatus("Open cancelled")')
        dialog.destroy()
        gtk.gdk.threads_leave()

    # Finally, here is our personalized main loop, 100% friendly
    # with "select" (although I am not using select here)!:
    clicks = -1
    while not Global.quit:

        again = False
        msg = web_recv()
        if msg:
            try:
                msg = from_json(msg)
            except ValueError:
                print "No valid JSON has been send.."
                continue

            again = True

            # Check if the message starts with lowercase viki. This indicates that there is a matching function with the same name in Python that should be executed.
            if msg['name'].startswith("viki"):
                try:
                    if msg['value'] == False:
                        locals()[msg['name']]()
                    else:
                        locals()[msg['name']](msg['value'])
                except KeyError:
                    web_send('updateStatus("Function '+msg['name']+' not found")')

        if again:
            pass
        else:
            time.sleep(0.1)
Beispiel #3
0
def main():
    start_gtk_thread()
    
    langcard_db = LangcardDB();

    # Create a proper file:// URL pointing to demo.xhtml:
    file = os.path.abspath('html/demo.xhtml')
    uri = 'file://' + urllib.pathname2url(file)
    browser, web_recv, web_send = \
        synchronous_gtk_message(launch_browser)(uri,
                                                quit_function=Global.set_quit)

    # Finally, here is our personalized main loop, 100% friendly
    # with "select" (although I am not using select here)!:
    last_second = time.time()
    uptime_seconds = 1
    clicks = 0
    while not Global.quit:
        # GETLIST
        # SETPHRA
        # GETRAND
        current_time = time.time()
        again = False
        msg = web_recv()

        if msg:
            print msg


        if msg and msg[0:7]=="GETRAND":
            randomword_array = langcard_db.langcardGetRandomWord();
            randonword_struct = {}
            randonword_struct['id'] = randomword_array[0];            
            randonword_struct['comments'] = randomword_array[1];
            randonword_struct['original'] = randomword_array[2];
            randonword_struct['translation'] = randomword_array[3];
            randonword_struct['phrase'] = randomword_array[4];
            randonword_struct['position'] = randomword_array[5];
            
            randomword_json = to_json(randonword_struct)
            randomword_json = randomword_json.replace('\'','')
            print randomword_json
            web_send("setRandomWord('%s')" % (randomword_json));
            continue;

        if msg and msg[0:7]=="SETPHRA":
            msg = from_json(msg[7:])
            langcard_db.langcardSetPhrase(msg);
            again = True
            continue

        if msg and msg[0:7]=="GETLIST":
            phrases = langcard_db.langcardGetPhraseList()
            previd=-1
            phraselist = {}

            for index in phrases:
                currentid=phrases[index][0]

                if (currentid!=previd):
                    phrase = {}
                    phrase['id'] = phrases[index][0]
                    phrase['phrase'] = phrases[index][4]
                    phrase['words'] = {}

                word = {}
                word['original'] = phrases[index][2];
                word['translation'] = phrases[index][3];
                word['comments'] = phrases[index][1];
                word['position'] = phrases[index][5];

                phrase['words'][len(phrase['words'])] = word;

                if (currentid!=previd):
                    phraselist[len(phraselist)] = phrase
              
                previd=currentid;

#            phraselist[len(phraselist)] = phrase
            phraselist = to_json(phraselist)

            phraselist = phraselist.replace('\'','')
            web_send("setList('%s')" % (phraselist));

        if again: pass
        else:     time.sleep(0.1)
Beispiel #4
0
def main():
    start_gtk_thread()
    # Changing working directory
    abspath = os.path.abspath(__file__)
    dname = os.path.dirname(abspath)
    os.chdir(dname)
    
    #collect sys info
    #release = open("/etc/release", "r").read()
    release = commands.getoutput('lsb_release -sd')
    release = release[1:-1]
    kernel = commands.getoutput('uname -r')
    if os.uname()[4] == 'x86_64':
      arch = '64-bit'
    else:
      arch = '32-bit'
    home = os.getenv("HOME")
    username = os.getenv("USER")
    desktop = get_desktop_name(os.getenv("DESKTOP_SESSION"))
    
    if desktop == 'Other':
      desktop = get_desktop_name2(os.getenv("XDG_CURRENT_DESKTOP"))
    
   
    #collect packages nad its status
    listapp = get_listapp()
    
    #TODO check if non-free and tainted enabled
    restricted_repos = "disabled"
    
   
    l={}
    l['name'] = _("Welcome to Mageia!")
    l['show'] = _("Show this window at startup")
    l['close'] = _("Close")
   
    l['release'] = release
    l['kernel_l'] = _("kernel:") 
    l['kernel'] = kernel
    l['arch_l'] = _("arch:")
    l['arch'] = arch
    l['desktop_l'] = _("Desktop:")
    l['desktop'] = desktop
    l['welcome_btn'] = _("Welcome")
    l['welcome'] = _("Welcome<!--user//-->")
    l['user'] = username
    l['welcome_msg'] = _("<p>Thank you for choosing Mageia!</p><p>We have put in a lot of effort to provide you with the best possible system. We hope you will have a good experience with Mageia. If you feel that our project is a good idea, we would also appreciate any contribution you can make to it for next versions.</p><p>To find out how you can help <a class='weblink' href='http://www.mageia.org/en/contribute/'>click here</a>.</p><p>Don't forget to tell your friends about Mageia.</p>")
    l['mcc'] = _("Mageia Control Center")
    l['conf_update'] = _("Configure media sources and update system")
    l['inst_remove'] = _("Install and remove software")
    l['h_documentation'] = _("Documentation")
    l['features'] = _("New Features")
    l['relnotes'] = _("Release Notes")
    l['errata'] = _("Errata")
    l['newcomers'] = _("Newcomers Howto")
    l['h_support'] = _("Support")
    l['forum'] = _("Forums")
    l['wiki'] = _("Wiki")
    l['chat'] = _("Chat Room")
    l['bugs'] = _("Bugzilla")
    l['h_community'] = _("Community")
    l['comm_center'] = _("Community Center")
    l['contribute'] = _("Contribute")
    l['donate'] = _("Donations")
    l['joinus'] = _("Join us!")
    l['mccdesc'] = _("Mageia Control Center (aka drakconf) is a set of tools to help you configure your system")
    l['SM'] = _("Software Management")
    l['Oa'] = _("Online administration")
    l['H'] = _("Hardware")
    l['NI'] = _("Network & Internet")
    l['S'] = _("System")
    l['NS'] = _("Network Sharing")
    l['LD'] = _("Local Disks")
    l['Sec'] = _("Security")
    l['B'] = _("Boot")
    l['adminpass'] = _("Administrator password is needed")
    l['userpass'] = _("User password is needed")
    l['conf_media'] = _("Configure media sources ...")
    l['mag_media'] = _("Mageia official repositories contain:")
    l['core'] = _("<span class='label green'>core</span> - the free-open-source packages, i.e. software licensed under a free-open-source license")
    l['nonfree'] = _("<span class='label red'>non-free</span> - some programs which are not free, or closed source. For example this repository includes Nvidia and ATI graphics card proprietary drivers, firmware for various WiFi cards, etc")
    l['tainted'] = _("<span class='label red'>tainted</span> - includes packages released under a free license. However, they may infringe on patents and copyright laws in some countries, e.g. multimedia codecs needed to play various audio/video files; packages needed to play commercial video DVD, etc. ")
    l['note'] = _("<strong>Note!</strong> non-free and tainted are not enabled by default.")
    l['editss'] = _("Edit software sources")
    l['updsys'] = _("... and update system")
    l['chkupd'] = _("Check system updates")
    l['guirpmdrake'] = _("GUI - RPMDrake")
    l['rpmdrake_desc'] = _("<span class='label green'>Rpmdrake</span> is a program for installing, uninstalling and updating packages. It is the graphical user interface of <span class='label green'>urpmi</span>")
    l['readmore'] = _("read more (wiki)")
    l['r_rpmdrake'] = _("RPMdrake")
    l['urpmi'] = _("URPMI - from command line")
    l['r_term'] = _("Terminal")
    l['small_selection'] = _("This is just small selection of popular packages, for more run")
    l['featured'] = _("Featured")
    l['games'] = _("Games")
    l['internet'] = _("Internet")
    l['video'] = _("Video")
    l['audio'] = _("Audio")
    l['office'] = _("Office")
    l['graphics'] = _("Graphics")
    l['system'] = _("System")
    l['programming'] = _("Programming")
    l['selected'] = _("Selected packages:")
    l['inst_sel'] = _("Install selected")
    l['youcan'] = _("You can always launch MageiaWelcome from menu")    
    
    l['rpm_install'] = _("Applications")
    l['webchat_btn'] = _("WebChat")
    l['applist'] = listapp
    l['bodyclass'] = restricted_repos
    l['besure_repos'] = _("Be sure you have enabled <a>online repositories</a>")
    
    
    if os.path.exists(home + "/.mrwelcome/norun.flag"):
            l['checked'] = ("")
    else:
            l['checked'] = ("CHECKED")
   
    
    l['home'] = home
    
    
    l['about'] = _("About")
    
    # Translations
   
    file = os.path.abspath('index.html')
    template = open(file).read()
    html = string.Template(template).safe_substitute(l)
    
    browser, web_recv, web_send = \
        synchronous_gtk_message(launch_browser)(html, quit_function=Global.set_quit)

    # Finally, here is our personalized main loop
  
    while not Global.quit:
     
        again = False
        msg = web_recv()
        if msg:
            msg = from_json(msg)
            again = True
            if msg == "close":
	      my_quit_wrapper()
	    elif msg == "checkbox checked":
	      if os.path.exists(home + "/.mrwelcome/norun.flag"):
		  os.system("rm -rf " + home + "/.mrwelcome/norun.flag")
	    elif msg == "checkbox unchecked":
	      os.system("mkdir -p " + home + "/.mrwelcome")
	      os.system("touch " + home + "/.mrwelcome/norun.flag")
	    elif msg.startswith("http"):
	      os.system("xdg-open " + msg)
	    elif msg == "irc":
	      irc_client = get_irc_client()
	      if irc_client == "none":
		if desktop == "KDE":
		  subprocess.Popen("gurpmi konversation", shell=True)
		else:
		  subprocess.Popen("gurpmi hexchat", shell=True)
	      else: os.system(irc_client)
	    elif msg.startswith("run"):
	      args = shlex.split(msg)
	      args.pop(0)
	      print args
	      if args[0] == "xvt":
		os.chdir(home)
	      subprocess.Popen(args)
	    
	    elif msg.startswith("gurpmi"):
		print msg
		args = shlex.split(msg)
		cat = args.pop(1)
		print args
		proc = subprocess.Popen(args, stdout=subprocess.PIPE)
		proc.wait()
		print proc.returncode
		if (proc.returncode == 0):
		  listapp = get_listapp()
		  web_send('$("ul#lista_applikacji").html("'+listapp+'");$("li#'+cat+'").trigger("click");')
		else: pass
	    elif msg.startswith("install_selected"):
		print msg
		msg2 = msg.replace('install_selected','gurpmi')
		args = shlex.split(msg2)
		cat = args.pop(1)
		print args
		proc = subprocess.Popen(args, stdout=subprocess.PIPE)
		proc.wait()
		print proc.returncode
		if (proc.returncode == 0):
		  listapp = get_listapp()
		  web_send('$("ul#lista_applikacji").html("'+listapp+'");$("li#'+cat+'").trigger("click");')
		else: pass
        if again: pass
        else:     time.sleep(0.1)