Example #1
0
    def __create_window(self):
        # Upper center window
        x = (self.winfo_screenwidth() / 2) - 100
        y = (self.winfo_screenheight() / 3) - 45
        self.geometry('+%d+%d' % (x, y))

        # Set min/max sizing for resizing
        self.minsize(width=400, height=105)
        self.maxsize(width=1600, height=105)

        window_colour = 'grey90'
        self.configure(background=window_colour)

        # Frame 1
        self.__frame1 = tk.Frame(self, background=window_colour)
        self.__input_label_value = tk.StringVar(value='Input:')
        self.__input_label = ttk.Label(self.__frame1,
                                       textvariable=self.__input_label_value,
                                       justify='left',
                                       anchor='w',
                                       font=('Helvetica', 16),
                                       width=10,
                                       background=window_colour)
        self.__input_label.pack(fill=tk.X, expand=True)

        self.__frame1.pack(fill=tk.X, expand=True, padx=5, pady=5)

        # Frame 2
        self.__frame2 = tk.Frame(self, background=window_colour)

        self.__input = tk.StringVar()
        self.__input_field = tk.Entry(self.__frame2, textvariable=self.__input)
        self.__input_field.pack(fill=tk.X, expand=True)

        self.__frame2.pack(fill=tk.X, expand=True, padx=5)

        # Frame 3
        self.__frame3 = tk.Frame(self, background=window_colour)
        self.__button_cancel = tk.Button(self.__frame3,
                                         text='Cancel',
                                         justify='center',
                                         anchor='ne',
                                         highlightbackground=window_colour,
                                         command=self.__event_button_cancel)
        self.__button_cancel.pack(side=tk.RIGHT)

        self.__button_ok = tk.Button(self.__frame3,
                                     text='OK',
                                     justify='center',
                                     anchor='ne',
                                     highlightbackground=window_colour,
                                     command=self.__event_button_ok)
        self.__button_ok.pack(side=tk.RIGHT)
        self.__frame3.pack(fill=tk.X, expand=True, padx=5, pady=5)

        if 'NSRunningApplication' in dir():
            app = NSRunningApplication.runningApplicationWithProcessIdentifier_(
                os.getpid())
            app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps)
Example #2
0
def force_quit_applicaiton(bid):
    """force an application to quit for emergency workflows"""
    # use API to assign a variable for the running API so we can FORCE terminate it
    apps = NSRunningApplication.runningApplicationsWithBundleIdentifier_(bid)
    # API returns an array always, must iterate through it
    for app in apps:
        # terminate the app
        app.forceTerminate()
Example #3
0
    def main(self):
        app = NSRunningApplication.runningApplicationWithProcessIdentifier_(os.getpid())
        app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps)

        if self.panel.runModal() == NSOKButton:
            return self.panel.filename()
        else:
            return None
Example #4
0
def check_if_running(bid):
    """Test to see if an app is running by bundle ID"""
    # macOS API to check if an app bundle is running or not
    app = NSRunningApplication.runningApplicationsWithBundleIdentifier_(bid)
    # return True if running, False if not
    if app:
        return True
    if not app:
        return False
Example #5
0
def wait_for_userspace():
    """this function will check to see if the Dock and Finder are present to ensure user space
    has fully loaded.  This will stop that race condition"""
    # give the system a few seconds to log into user space
    time.sleep(10.0)
    # check to see if still in the "mac buddy" user context
    while USER == '_mbsetupuser':
        logging.info('detected Mac Buddy user context...')
        time.sleep(1.0)
        if USER != '_mbsetupuser':
            break
    # test to make sure both the Finder and Dock are running by bundle ID to ensure user space is fully loaded
    app1 = None
    app2 = None
    while not all([app1, app2]):
        app1 = NSRunningApplication.runningApplicationsWithBundleIdentifier_('com.apple.dock')
        app2 = NSRunningApplication.runningApplicationsWithBundleIdentifier_('com.apple.finder')
        logging.info('waiting for apps to appear running..')
        time.sleep(0.5)
Example #6
0
def platform_specific_setup():
    try:
        from Cocoa import NSRunningApplication, NSApplicationActivateIgnoringOtherApps
        import os

        app = NSRunningApplication.runningApplicationWithProcessIdentifier_(
            os.getpid())
        app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps)

    except ModuleNotFoundError:
        print("cocoa framework not found!")
Example #7
0
def quit_application(bid):
    """quits apps using NSRunningApplication"""
    # use API to assign a variable for the running API so we can terminate it
    apps = NSRunningApplication.runningApplicationsWithBundleIdentifier_(bid)
    # API returns an array always, must iterate through it
    for app in apps:
        # terminate the app
        app.terminate()
        # if the app does not terminate in 3 seconds gracefully force it
        time.sleep(3)
        if not app.isTerminated():
            app.forceTerminate()
Example #8
0
	def createWindow(self):

		# Upper center window
		x = (self.winfo_screenwidth() / 2) - 100
		y = (self.winfo_screenheight() / 3) - 45
		self.geometry("+%d+%d" % (x, y))

		# Set min/max sizing for resizing
		self.minsize(width=200, height=105)
		self.maxsize(width=1600, height=105)

		windowcolor = 'grey90'
		self.configure(background=windowcolor)

		# Frame 1
		self.frame1 = tk.Frame(self, background=windowcolor)
		self.userlabel = ttk.Label(self.frame1, text="Username", justify="left", anchor="w", font=("Helvetica", 16), width=10, background=windowcolor)
		self.userlabel.pack(side="left")

		self.username = tk.StringVar()  # Password variable
		self.userfield = tk.Entry(self.frame1, textvariable=self.username)
		self.userfield.pack(fill=tk.X, expand=True, side=tk.RIGHT)

		self.frame1.pack(fill=tk.X, expand=True, padx=5, pady=5)

		# Frame 2
		self.frame2 = tk.Frame(self, background=windowcolor)
		self.passlabel = ttk.Label(self.frame2, text="Password", justify="left", anchor="w", font=("Helvetica", 16), width=10, background=windowcolor)
		self.passlabel.pack(side="left")

		self.password = tk.StringVar()  # Password variable
		self.passfield = tk.Entry(self.frame2, textvariable=self.password, show="*")
		self.passfield.pack(fill=tk.X, expand=True, side=tk.RIGHT)

		self.frame2.pack(fill=tk.X, expand=True, padx=5)

		# Frame 3
		self.frame3 = tk.Frame(self, background=windowcolor)
		self.button2 = tk.Button(self.frame3, text='Cancel', justify="center", anchor="ne", highlightbackground=windowcolor, command=self.buttonCancel)
		self.button2.pack(side=tk.RIGHT)

		self.button1 = tk.Button(self.frame3, text='OK', justify="center", anchor="ne", highlightbackground=windowcolor, command=self.buttonOK)
		self.button1.pack(side=tk.RIGHT)
		self.frame3.pack(fill=tk.X, expand=True, padx=5, pady=5)

		# Try to set window focus
		try:
			from Cocoa import NSRunningApplication, NSApplicationActivateIgnoringOtherApps
		except:
			print ("pip3 install pyobjc")
			sys.exit()
		app = NSRunningApplication.runningApplicationWithProcessIdentifier_(os.getpid())
		app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps)
def wait_for_userspace():
    """this function will check to see if the Dock and Finder are present to ensure user space
    has fully loaded.  This will stop that race condition"""
    # give the system a few seconds to log into user space
    time.sleep(7.0)
    # check to see if still in the "mac buddy" user context
    while USER == "_mbsetupuser":
        user, uid, gid = SCDynamicStoreCopyConsoleUser(None, None, None)
        logging.info("detected Mac Buddy user context...")
        time.sleep(1.0)
        if user != "_mbsetupuser":
            break
    # test to make sure both the Finder and Dock are running by bundle ID to ensure user space is fully loaded
    app1 = None
    app2 = None
    while not all([app1, app2]):
        app1 = NSRunningApplication.runningApplicationsWithBundleIdentifier_(
            "com.apple.dock")
        app2 = NSRunningApplication.runningApplicationsWithBundleIdentifier_(
            "com.apple.finder")
        logging.info("waiting for apps to appear running..")
        time.sleep(0.5)
Example #10
0
def set_alert_panel(message, info):
    buttons = ["OK", "Cancel"]
    alert = NSAlert.alloc().init()
    alert.setMessageText_(message)
    alert.setInformativeText_(info)
    alert.setAlertStyle_(NSInformationalAlertStyle)

    app = NSRunningApplication.runningApplicationWithProcessIdentifier_(os.getpid())
    app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps)

    for button in buttons:
        alert.addButtonWithTitle_(button)

    buttonPressed = alert.runModal()
    return buttonPressed
Example #11
0
	def createWindow(self):

		# Upper center window
		x = (self.winfo_screenwidth() / 2) - 200
		y = (self.winfo_screenheight() / 3) - 45
		self.geometry("+%d+%d" % (x, y))

		# Set min/max sizing for resizing
		self.minsize(width=400, height=550)
		self.maxsize(width=2400, height=2000)

		windowcolor = 'grey90'
		self.configure(background=windowcolor)

		# Frame 1
		self.frame1 = tk.Frame(self, background=windowcolor)
		self.inputlabelValue = tk.StringVar(value="Input:")
		self.inputlabel = ttk.Label(self.frame1,  textvariable=self.inputlabelValue, justify="left", anchor="w", font=("Helvetica", 16), width=10, background=windowcolor)
		self.inputlabel.pack(fill=tk.X, expand=True)

		self.frame1.pack(fill=tk.X, padx=5, pady=5)

		# Frame 2
		self.frame2 = tk.Frame(self, background=windowcolor)
		self.input = tk.StringVar()
		self.inputfield = tk.Text(self.master, yscrollcommand=True, font=("Helvetica", 16),background="white")
		self.inputfield.pack(fill=tk.BOTH, expand=True)

		self.frame2.pack(fill=tk.BOTH, padx=5)

		# Frame 3
		self.frame3 = tk.Frame(self, background=windowcolor)
		self.button2 = tk.Button(self.frame3, text='Cancel', justify="center", anchor="ne", highlightbackground=windowcolor, command=self.buttonCancel)
		self.button2.pack(side=tk.RIGHT)

		self.button1 = tk.Button(self.frame3, text='OK', justify="center", anchor="ne", highlightbackground=windowcolor, command=self.buttonOK)
		self.button1.pack(side=tk.RIGHT)
		self.frame3.pack(fill=tk.X, padx=5)

		# Try to set window focus
		try:
			from Cocoa import NSRunningApplication, NSApplicationActivateIgnoringOtherApps
		except:
			print ("pip3 install pyobjc")
			sys.exit()
		app = NSRunningApplication.runningApplicationWithProcessIdentifier_(os.getpid())
		app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps)
Example #12
0
def set_file_dialog():
    """
    Cocoa Save File Dialog obx
    :return:
    """
    panel = NSSavePanel.savePanel()
    panel.setCanCreateDirectories_(True)
    panel.setCanChooseDirectories_(True)
    panel.setCanChooseFiles_(True)

    app = NSRunningApplication.runningApplicationWithProcessIdentifier_(os.getpid())
    app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps)

    if panel.runModal() == NSOKButton:
        return panel.filename()
    else:
        return None
    def __init__(self, args):
        self.server = args.server
        self.user = args.user
        self.password = args.password
        self.id = args.id
        self.auth = self.get_authorization_header()
        self.serial_number = self.get_serial_number()
        self.extension_attribute = self.get_extension_attribute()
        self.extension_attribute_name = self.extension_attribute[
            'computer_extension_attribute']['name']
        self.testing_groups = [
            choice for choice in
            self.extension_attribute['computer_extension_attribute']
            ['input_type']['popup_choices']
        ]
        self.root = tk.Tk()
        self.root.attributes("-topmost", True)
        self.root.title("Choose Testing Group")
        self.testing_groups_var = tk.StringVar(self.root)
        self.testing_groups_var.set(None)
        self.l1 = tk.Label(self.root, text="Testing Groups:", padx=10,
                           pady=5).grid(row=0)
        # self.e1 = tk.Entry(self.root, width=25)
        self.e1 = tk.OptionMenu(self.root, self.testing_groups_var,
                                *self.testing_groups)

        self.e1.grid(row=0, column=1, padx=10, sticky=tk.E)

        tk.Button(self.root,
                  text="Continue",
                  command=self.set_extension_attribute).grid(row=4,
                                                             column=1,
                                                             padx=4,
                                                             pady=4,
                                                             sticky=tk.E)
        self.center()
        self.app = NSRunningApplication.runningApplicationWithProcessIdentifier_(
            os.getpid())
        self.app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps)
        self.bundle = NSBundle.mainBundle()
        if self.bundle:
            self.info = self.bundle.localizedInfoDictionary(
            ) or self.bundle.infoDictionary()
            if self.info and self.info['CFBundleName'] == 'Python':
                self.info['CFBundleName'] = "Testing Group Enrollment"
        self.root.mainloop()
Example #14
0
def get_directory_dialog():
    """
    Cocoa Open Directory Dialog box
    :return:
    """
    panel = NSOpenPanel.openPanel()
    panel.setCanCreateDirectories_(True)
    panel.setCanChooseDirectories_(True)
    panel.setCanChooseFiles_(False)

    app = NSRunningApplication.runningApplicationWithProcessIdentifier_(os.getpid())
    app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps)

    if panel.runModal() == NSOKButton:
        return panel.directory()
    else:
        return None
Example #15
0
    def doGUI(self, hostname=None):
        self.master = Tk()
        self.master.title('Blessclient - MFA')
        textmsg = 'Enter your AWS MFA code: '
        if hostname:
            textmsg = 'Enter your AWS MFA code to connect to {}: '.format(
                hostname)
        Label(self.master, text=textmsg).grid(row=0)
        self.e1 = Entry(self.master)
        self.e1.grid(row=0, column=1, padx=4)
        Button(self.master,
               text='OK',
               command=self.show_entry_fields,
               default=ACTIVE).grid(row=3, column=0, sticky=W, pady=4)
        Button(self.master, text='Cancel', command=self.quit).grid(row=3,
                                                                   column=1,
                                                                   sticky=W,
                                                                   pady=4)

        self.center()
        self.master.bind('<Return>', self.show_entry_fields)
        self.master.lift()
        self.master.attributes('-topmost', True)
        self.master.focus_force()
        self.e1.focus_set()
        if platform.system() == 'Darwin':
            try:
                from Cocoa import (NSRunningApplication,
                                   NSApplicationActivateIgnoringOtherApps)

                app = NSRunningApplication.runningApplicationWithProcessIdentifier_(
                    os.getpid())
                app.activateWithOptions_(
                    NSApplicationActivateIgnoringOtherApps)
            except ImportError:
                pass

        mainloop()
Example #16
0
 def SetForegroundWindow(pid):
     target_window = NSRunningApplication.runningApplicationWithProcessIdentifier_(
         pid)
     target_window.activateWithOptions_(
         NSApplicationActivateIgnoringOtherApps)
Example #17
0
 def show(self):
     # Get focus of the window
     NSRunningApplication.runningApplicationWithProcessIdentifier_(
         os.getpid()).activateWithOptions_(
             NSApplicationActivateIgnoringOtherApps)
     self.root.mainloop()
Example #18
0
    def __init__(self, plists=[]):
        # Create the new tk object
        self.tk = tk.Tk()
        self.tk.title("Convert Values")
        self.tk.minsize(width=640, height=130)
        self.tk.resizable(True, False)
        self.tk.columnconfigure(2, weight=1)
        self.tk.columnconfigure(3, weight=1)
        # Build the Hex <--> Base64 converter
        f_label = tk.Label(self.tk, text="From:")
        f_label.grid(row=0, column=0, padx=10, pady=10)
        t_label = tk.Label(self.tk, text="To:")
        t_label.grid(row=1, column=0, padx=10, pady=10)

        # Create the settings window
        self.settings_window = tk.Toplevel(self.tk)
        self.settings_window.title("ProperTree Settings")
        w = 380
        h = 150
        self.settings_window.minsize(width=w, height=h)
        self.settings_window.resizable(True, False)
        self.settings_window.columnconfigure(0, weight=1)
        self.settings_window.columnconfigure(1, weight=1)
        # Let's also center the window
        x = self.settings_window.winfo_screenwidth() // 2 - w // 2
        y = self.settings_window.winfo_screenheight() // 2 - h // 2
        self.settings_window.geometry("{}x{}+{}+{}".format(w, h, x, y))
        # Let's add some checkboxes and stuffs
        self.expand_on_open = tk.IntVar()
        self.use_xcode_data = tk.IntVar()
        self.sort_dict_keys = tk.IntVar()
        self.expand_check = tk.Checkbutton(
            self.settings_window,
            text="Expand Children When Opening Plist",
            variable=self.expand_on_open,
            command=self.expand_command)
        self.xcode_check = tk.Checkbutton(
            self.settings_window,
            text="Use Xcode-Style <data> Tags (Inline) in XML Plists",
            variable=self.use_xcode_data,
            command=self.xcode_command)
        self.sort_check = tk.Checkbutton(self.settings_window,
                                         text="Ignore Dictionary Key Order",
                                         variable=self.sort_dict_keys,
                                         command=self.sort_command)
        self.expand_check.grid(row=0,
                               column=0,
                               columnspan=2,
                               sticky="w",
                               padx=10,
                               pady=(10, 0))
        self.xcode_check.grid(row=1,
                              column=0,
                              columnspan=2,
                              sticky="w",
                              padx=10)
        self.sort_check.grid(row=2,
                             column=0,
                             columnspan=2,
                             sticky="w",
                             padx=10)
        self.plist_type_string = tk.StringVar(self.settings_window)
        self.plist_type_menu = tk.OptionMenu(self.settings_window,
                                             self.plist_type_string,
                                             "XML",
                                             "Binary",
                                             command=self.change_plist_type)
        plist_label = tk.Label(self.settings_window,
                               text="Default New Plist Type:")
        plist_label.grid(row=3, column=0, sticky="w", padx=10)
        self.plist_type_menu.grid(row=3, column=1, sticky="we", padx=10)
        reset_settings = tk.Button(self.settings_window,
                                   text="Reset To Defaults",
                                   command=self.reset_settings)
        reset_settings.grid(row=4, column=1, sticky="e", padx=10, pady=(0, 10))

        # Setup the from/to option menus
        f_title = tk.StringVar(self.tk)
        t_title = tk.StringVar(self.tk)
        f_title.set("Base64")
        t_title.set("Hex")
        f_option = tk.OptionMenu(self.tk,
                                 f_title,
                                 "Ascii",
                                 "Base64",
                                 "Decimal",
                                 "Hex",
                                 command=self.change_from_type)
        t_option = tk.OptionMenu(self.tk,
                                 t_title,
                                 "Ascii",
                                 "Base64",
                                 "Decimal",
                                 "Hex",
                                 command=self.change_to_type)
        self.from_type = "Base64"
        self.to_type = "Hex"
        f_option.grid(row=0, column=1, sticky="we")
        t_option.grid(row=1, column=1, sticky="we")

        self.f_text = tk.Entry(self.tk)
        self.f_text.delete(0, tk.END)
        self.f_text.insert(0, "")
        self.f_text.grid(row=0,
                         column=2,
                         columnspan=2,
                         sticky="we",
                         padx=10,
                         pady=10)

        self.t_text = tk.Entry(self.tk)
        self.t_text.configure(state='normal')
        self.t_text.delete(0, tk.END)
        self.t_text.insert(0, "")
        self.t_text.configure(state='readonly')
        self.t_text.grid(row=1,
                         column=2,
                         columnspan=2,
                         sticky="we",
                         padx=10,
                         pady=10)

        self.c_button = tk.Button(self.tk,
                                  text="Convert",
                                  command=self.convert_values)
        self.c_button.grid(row=2, column=3, sticky="e", padx=10, pady=10)

        self.f_text.bind("<Return>", self.convert_values)
        self.f_text.bind("<KP_Enter>", self.convert_values)

        self.start_window = None

        # Regex to find the processor serial numbers when
        # opened from the Finder
        self.regexp = re.compile(r"^-psn_[0-9]+_[0-9]+$")

        # Setup the menu-related keybinds - and change the app name if needed
        key = "Control"
        sign = "Ctrl+"
        if str(sys.platform) == "darwin":
            # Remap the quit function to our own
            self.tk.createcommand('::tk::mac::Quit', self.quit)
            self.tk.createcommand("::tk::mac::OpenDocument",
                                  self.open_plist_from_app)
            self.tk.createcommand("::tk::mac::ReopenApplication",
                                  self.open_plist_from_app)
            # Import the needed modules to change the bundle name and force focus
            try:
                from Foundation import NSBundle
                from Cocoa import NSRunningApplication, NSApplicationActivateIgnoringOtherApps
                app = NSRunningApplication.runningApplicationWithProcessIdentifier_(
                    os.getpid())
                app.activateWithOptions_(
                    NSApplicationActivateIgnoringOtherApps)
                bundle = NSBundle.mainBundle()
                if bundle:
                    info = bundle.localizedInfoDictionary(
                    ) or bundle.infoDictionary()
                    if info and info['CFBundleName'] == 'Python':
                        info['CFBundleName'] = "ProperTree"
            except:
                pass
            key = "Command"
            sign = key + "+"

        self.tk.protocol("WM_DELETE_WINDOW", self.close_window)
        self.settings_window.protocol("WM_DELETE_WINDOW", self.close_window)
        # Close initial windows
        self.tk.withdraw()
        self.settings_window.withdraw()

        self.default_windows = (self.tk, self.settings_window)

        if str(sys.platform) == "darwin":
            # Setup the top level menu
            file_menu = tk.Menu(self.tk)
            main_menu = tk.Menu(self.tk)
            main_menu.add_cascade(label="File", menu=file_menu)
            file_menu.add_command(label="New ({}N)".format(sign),
                                  command=self.new_plist)
            file_menu.add_command(label="Open ({}O)".format(sign),
                                  command=self.open_plist)
            file_menu.add_command(label="Save ({}S)".format(sign),
                                  command=self.save_plist)
            file_menu.add_command(label="Save As ({}Shift+S)".format(sign),
                                  command=self.save_plist_as)
            file_menu.add_command(label="Duplicate ({}D)".format(sign),
                                  command=self.duplicate_plist)
            file_menu.add_command(label="Reload From Disk ({}L)".format(sign),
                                  command=self.reload_from_disk)
            file_menu.add_separator()
            file_menu.add_command(label="OC Snapshot ({}R)".format(sign),
                                  command=self.oc_snapshot)
            file_menu.add_command(
                label="OC Clean Snapshot ({}Shift+R)".format(sign),
                command=self.oc_clean_snapshot)
            file_menu.add_separator()
            file_menu.add_command(label="Convert Window ({}T)".format(sign),
                                  command=self.show_convert)
            file_menu.add_command(label="Strip Comments ({}M)".format(sign),
                                  command=self.strip_comments)
            file_menu.add_separator()
            file_menu.add_command(
                label="Toggle Find/Replace Pane ({}F)".format(sign),
                command=self.hide_show_find)
            file_menu.add_command(
                label="Toggle Plist/Data Type Pane ({}P)".format(sign),
                command=self.hide_show_type)
            file_menu.add_separator()
            file_menu.add_command(label="Settings ({},)".format(sign),
                                  command=self.show_settings)
            file_menu.add_separator()
            file_menu.add_command(label="Quit ({}Q)".format(sign),
                                  command=self.quit)
            self.tk.config(menu=main_menu)

        # Set bindings
        self.tk.bind("<{}-w>".format(key), self.close_window)
        self.settings_window.bind("<{}-w>".format(key), self.close_window)
        self.tk.bind_all("<{}-n>".format(key), self.new_plist)
        self.tk.bind_all("<{}-o>".format(key), self.open_plist)
        self.tk.bind_all("<{}-s>".format(key), self.save_plist)
        self.tk.bind_all("<{}-S>".format(key), self.save_plist_as)
        self.tk.bind_all("<{}-d>".format(key), self.duplicate_plist)
        self.tk.bind_all("<{}-t>".format(key), self.show_convert)
        self.tk.bind_all("<{}-z>".format(key), self.undo)
        self.tk.bind_all("<{}-Z>".format(key), self.redo)
        self.tk.bind_all("<{}-m>".format(key), self.strip_comments)
        self.tk.bind_all("<{}-r>".format(key), self.oc_snapshot)
        self.tk.bind_all("<{}-R>".format(key), self.oc_clean_snapshot)
        self.tk.bind_all("<{}-l>".format(key), self.reload_from_disk)
        self.tk.bind_all("<{}-comma>".format(key), self.show_settings)
        if not str(sys.platform) == "darwin":
            # Rewrite the default Command-Q command
            self.tk.bind_all("<{}-q>".format(key), self.quit)

        cwd = os.getcwd()
        os.chdir(os.path.dirname(os.path.realpath(__file__)))
        #
        # Load the settings - current available settings are:
        #
        # last_window_width:         width value (default is 640)
        # last_window_height:        height value (default is 480)
        # expand_all_items_on_open:  bool
        # sort_dict:                 bool, false = OrderedDict
        # xcode_data:                bool, true = <data>XXXX</data>, false = different lines
        # new_plist_default_type:    string, XML/Binary
        #
        self.settings = {}
        try:
            if os.path.exists("Scripts/settings.json"):
                self.settings = json.load(open("Scripts/settings.json"))
        except:
            pass
        os.chdir(cwd)

        # Setup the settings page to reflect our settings.json file

        self.allowed_types = ("XML", "Binary")
        self.update_settings()

        # Wait before opening a new document to see if we need to.
        # This was annoying to debug, but seems to work.
        self.tk.after(100, lambda: self.check_open(plists))

        # Start our run loop
        tk.mainloop()
Example #19
0
    def create_gui(self):
        self.root = Tk()
        self.root.wm_title("CoilSnake " + information.VERSION)

        if platform.system() == "Windows":
            self.root.tk.call("wm", "iconbitmap", self.root._w,
                              asset_path(["images", "CoilSnake.ico"]))
        elif platform.system() == "Darwin":
            # Workaround - Raise the window
            from Cocoa import NSRunningApplication, NSApplicationActivateIgnoringOtherApps

            app = NSRunningApplication.runningApplicationWithProcessIdentifier_(
                os.getpid())
            app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps)
        else:
            self.iconphoto_params = (
                True,
                ImageTk.PhotoImage(file=asset_path(["images", "16.png"])),
                ImageTk.PhotoImage(file=asset_path(["images", "22.png"])),
                ImageTk.PhotoImage(file=asset_path(["images", "24.png"])),
                ImageTk.PhotoImage(file=asset_path(["images", "32.png"])),
                ImageTk.PhotoImage(file=asset_path(["images", "48.png"])),
                ImageTk.PhotoImage(file=asset_path(["images", "64.png"])),
                ImageTk.PhotoImage(file=asset_path(["images", "128.png"])),
                ImageTk.PhotoImage(file=asset_path(["images", "256.png"])))
            self.root.wm_iconphoto(*self.iconphoto_params)

        self.create_menubar()

        self.notebook = tkinter.ttk.Notebook(self.root)

        decompile_frame = self.create_decompile_frame(self.notebook)
        self.notebook.add(decompile_frame, text="Decompile")

        compile_frame = self.create_compile_frame(self.notebook)
        self.notebook.add(compile_frame, text="Compile")

        upgrade_frame = self.create_upgrade_frame(self.notebook)
        self.notebook.add(upgrade_frame, text="Upgrade")

        decompile_script_frame = self.create_decompile_script_frame(
            self.notebook)
        self.notebook.add(decompile_script_frame, text="Decompile Script")

        patcher_patch_frame = self.create_apply_patch_frame(self.notebook)
        self.notebook.add(patcher_patch_frame, text="Apply Patch")

        patcher_create_frame = self.create_create_patch_frame(self.notebook)
        self.notebook.add(patcher_create_frame, text="Create Patch")

        self.notebook.pack(fill=X)
        self.notebook.select(self.preferences.get_default_tab())

        self.progress_bar = CoilSnakeGuiProgressBar(self.root,
                                                    orient=HORIZONTAL,
                                                    mode='determinate')
        self.progress_bar.pack(fill=X)

        console_frame = Frame(self.root)

        scrollbar = Scrollbar(console_frame)
        scrollbar.pack(side=RIGHT, fill=Y)

        self.console = ThreadSafeConsole(console_frame, width=80, height=8)
        self.console.pack(fill=BOTH, expand=1)
        scrollbar.config(command=self.console.yview)
        self.console.config(yscrollcommand=scrollbar.set)
        console_frame.pack(fill=BOTH, expand=1)

        def selectall_text(event):
            event.widget.tag_add("sel", "1.0", "end")

        self.root.bind_class("Text", "<Control-a>", selectall_text)

        def selectall_entry(event):
            event.widget.selection_range(0, END)

        self.root.bind_class("Entry", "<Control-a>", selectall_entry)

        def tab_changed(event):
            # Do this so some random element in the tab isn't selected upon tab change
            self.notebook.focus()

            ## Recalculate the height of the notebook depending on the contents of the new tab

            # Ensure the dimensions of the widgets are up to date
            self.notebook.update_idletasks()

            # Get the width and height of the window, so we can reset it later
            width = self.root.winfo_width()
            height = self.root.winfo_height()

            # Set the notebook height to the selected tab's requested height
            tab_window_name = self.notebook.select()
            tab = self.notebook.nametowidget(tab_window_name)
            tab_height = tab.winfo_reqheight()
            self.notebook.configure(height=tab_height)

            # Keeps the window from changing size
            self.root.geometry("{}x{}".format(width, height))

        self.notebook.bind("<<NotebookTabChanged>>", tab_changed)

        self.console_stream = self.console

        setup_logging(quiet=False, verbose=False, stream=self.console_stream)
        self.refresh_debug_logging()
        self.load_geometry()
        self.root.protocol("WM_DELETE_WINDOW", self.save_geometry_and_close)
Example #20
0
    def createWindow(self):

        # Upper center window
        x = (self.winfo_screenwidth() / 2) - 100
        y = (self.winfo_screenheight() / 3) - 45
        self.geometry('+%d+%d' % (x, y))

        # Set min/max sizing for resizing
        self.minsize(width=400, height=130)
        self.maxsize(width=2400, height=130)

        windowcolor = 'grey90'
        self.configure(background=windowcolor)

        # Frame 1
        self.frame1 = tk.Frame(self, background=windowcolor)
        self.inputlabelValue = tk.StringVar(value='Input:')
        self.inputlabel = ttk.Label(self.frame1,
                                    textvariable=self.inputlabelValue,
                                    justify='left',
                                    anchor='w',
                                    font=('Helvetica', 16),
                                    width=10,
                                    background=windowcolor)
        self.inputlabel.pack(fill=tk.X, expand=True)

        self.frame1.pack(fill=tk.X, expand=True, padx=5, pady=5)

        # Frame 2
        self.frame2 = tk.Frame(self, background=windowcolor)
        self.input = tk.IntVar()
        self.inputfield = tk.Scale(self.master,
                                   variable=self.input,
                                   from_=0,
                                   to=100,
                                   orient='horizontal',
                                   troughcolor='white',
                                   showvalue=True,
                                   font=('Helvetica', 16),
                                   background=windowcolor)
        self.inputfield.pack(fill=tk.X, expand=True)

        self.frame2.pack(fill=tk.X, expand=True, padx=5)

        # Frame 3
        self.frame3 = tk.Frame(self, background=windowcolor)
        self.button2 = tk.Button(self.frame3,
                                 text='Cancel',
                                 justify='center',
                                 anchor='ne',
                                 highlightbackground=windowcolor,
                                 command=self.buttonCancel)
        self.button2.pack(side=tk.RIGHT)

        self.button1 = tk.Button(self.frame3,
                                 text='OK',
                                 justify='center',
                                 anchor='ne',
                                 highlightbackground=windowcolor,
                                 command=self.buttonOK)
        self.button1.pack(side=tk.RIGHT)
        self.frame3.pack(fill=tk.X, expand=True, padx=5)

        # Try to set window focus
        try:
            from Cocoa import NSRunningApplication, NSApplicationActivateIgnoringOtherApps
        except ImportError as err:
            print(err)
            print('pip3 install pyobjc')
            sys.exit()
        app = NSRunningApplication.runningApplicationWithProcessIdentifier_(
            os.getpid())
        app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps)