def build_prog_popup(self): pp = Popup(self) pp.part_text_set('title,text', _('Extracting files, please wait...')) pp.show() vbox = Box(self) pp.part_content_set('default', vbox) vbox.show() lb = Label(self, ellipsis=True, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ) vbox.pack_end(lb) lb.show() pb = Progressbar(pp, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ) vbox.pack_end(pb) pb.show() bt = Button(pp, text=_('Cancel')) bt.callback_clicked_add(lambda b: self.app.abort_operation()) pp.part_content_set('button1', bt) self.prog_pbar = pb self.prog_label = lb self.prog_popup = pp
def cb_popup_center_title_text_block_clicked_event(li, item, win): popup = Popup(win, size_hint_weight=EXPAND_BOTH) popup.text = "This Popup has title area and content area. " \ "When clicked on blocked event region, popup gets deleted" popup.part_text_set("title,text", "Title") popup.callback_block_clicked_add(cb_bnt_close, popup) popup.show()
def signal_clicked_cb(self, gl, item): pp = Popup(self._parent) pp.part_text_set('title,text', 'Signal content') en = Entry(self, text=prettify_if_needed(item.data['args'])) en.size_hint_weight = EVAS_HINT_EXPAND, EVAS_HINT_EXPAND en.size_hint_align = EVAS_HINT_FILL, EVAS_HINT_FILL en.size_hint_min = 800, 800 # TODO: this should be respected :/ en.editable = False en.scrollable = True pp.content = en bt = Button(pp, text="Close") bt.callback_clicked_add(lambda b: pp.delete()) pp.part_content_set('button2', bt) def prettify_clicked_cb(chk): options.pretty_output = chk.state en.text = prettify_if_needed(item.data['args']) ck = Check(pp, text="Prettify") ck.state = options.pretty_output ck.callback_changed_add(prettify_clicked_cb) pp.part_content_set('button1', ck) pp.show()
def cb_popup_center_title_text_1button(li, item, win): popup = Popup(win, size_hint_weight=EXPAND_BOTH) popup.text = "This Popup has content area and " \ "action area set, action area has one button Close" bt = Button(win, text="Close") bt.callback_clicked_add(cb_bnt_close, popup) popup.part_content_set("button1", bt) popup.show()
def __init__(self, canvas, title, text): n = Popup(canvas) n.part_text_set("title,text", title) n.text = text b = Button(canvas) b.text = "OK" b.callback_clicked_add(lambda x: n.delete()) n.part_content_set("button1", b) n.show()
def pw_error_popup(en): win = en.top_widget_get() popup = Popup(win) popup.size_hint_weight = evas.EVAS_HINT_EXPAND, evas.EVAS_HINT_EXPAND popup.part_text_set("title,text", "Error") popup.text = "Incorrect Password!<br>Please try again." log.error("eSudo Error: Incorrect Password. Please try again.") popup.timeout = 3.0 popup.show()
def showDialog(self, title, msg): dia = Popup(self) dia.part_text_set("title,text", title) dia.part_text_set("default", msg) bt = Button(dia, text="Ok") bt.callback_clicked_add(lambda b: dia.delete()) dia.part_content_set("button1", bt) dia.show()
def _confirm_delete(self, m, item): pp = Popup(self.top_widget, text=self._task.text) pp.part_text_set('title,text', 'Confirm task deletion?') btn = Button(pp, text='Cancel') btn.callback_clicked_add(lambda b: pp.delete()) pp.part_content_set('button1', btn) btn = Button(pp, text='Delete Task') btn.callback_clicked_add(self._delete_confirmed, pp) pp.part_content_set('button2', btn) pp.show()
def show_error_msg(self, msg): pop = Popup(self, text=msg) pop.part_text_set('title,text', _('Error')) btn = Button(self, text=_('Continue')) btn.callback_clicked_add(lambda b: pop.delete()) pop.part_content_set('button1', btn) btn = Button(self, text=_('Exit')) btn.callback_clicked_add(lambda b: self.app.exit()) pop.part_content_set('button2', btn) pop.show()
def __init__(self, canvas, exit_func): n = Popup(canvas) n.part_text_set("title,text", "Confirm exit") n.text = "Are you sure you wish to exit Epour?" b = Button(canvas) b.text = "Yes" b.callback_clicked_add(lambda x: exit_func()) n.part_content_set("button1", b) b = Button(canvas) b.text = "No" b.callback_clicked_add(lambda x: n.delete()) n.part_content_set("button2", b) n.show()
def cb_popup_center_title_text_2button_restack(li, item, win): popup = Popup(win, size_hint_weight=EXPAND_BOTH) popup.text = "When you click the 'Restack' button, " \ "an image will be located under this popup" popup.part_text_set("title,text", "Title") bt = Button(win, text="Restack") bt.callback_clicked_add(cb_btn_restack, popup) popup.part_content_set("button1", bt) bt = Button(win, text="Close") bt.callback_clicked_add(cb_bnt_close, popup) popup.part_content_set("button3", bt) popup.show()
def errorPopup(window, errorMsg): errorPopup = Popup(window, size_hint_weight=EXPAND_BOTH) errorPopup.callback_block_clicked_add(lambda obj: errorPopup.delete()) # Add a table to hold dialog image and text to Popup tb = Table(errorPopup, size_hint_weight=EXPAND_BOTH) errorPopup.part_content_set("default", tb) tb.show() # Add dialog-error Image to table need_ethumb() icon = Icon(errorPopup, thumb='True') icon.standard_set('dialog-warning') # Using gksudo or sudo fails to load Image here # unless options specify using preserving their existing environment. # may also fail to load other icons but does not raise an exception # in that situation. # Works fine using eSudo as a gksudo alternative, # other alternatives not tested try: dialogImage = Image(errorPopup, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_BOTH, file=icon.file_get()) tb.pack(dialogImage, 0, 0, 1, 1) dialogImage.show() except RuntimeError: # An error message is displayed for this same error # when aboutWin is initialized so no need to redisplay. pass # Add dialog text to table dialogLabel = Label(errorPopup, line_wrap=ELM_WRAP_WORD, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_BOTH) dialogLabel.text = errorMsg tb.pack(dialogLabel, 1, 0, 1, 1) dialogLabel.show() # Ok Button ok_btt = Button(errorPopup) ok_btt.text = "Ok" ok_btt.callback_clicked_add(lambda obj: errorPopup.delete()) ok_btt.show() # add button to popup errorPopup.part_content_set("button3", ok_btt) errorPopup.show()
def applyPressed(self, btn): with open(StartupApplicationsFile, 'w') as saf: for i in self.startupList.items_get(): saf.write(i.data["file"]) saf.write("\n") with open(StartupCommandsFile, 'w') as scf: lastI = self.commandsList.last_item_get() for i in self.commandsList.items_get(): if i != lastI: scf.write(i.text + " | \\ \n") else: scf.write(i.text) p = Popup(self, size_hint_weight=EXPAND_BOTH, timeout=3.0) p.text = "Changes Successfully Applied" p.show()
def cb_popup_center_title_content_3button(li, item, win): ic = Icon(win, file=os.path.join(img_path, "logo_small.png")) bt = Button(win, text="Content", content=ic) popup = Popup(win, size_hint_weight=EXPAND_BOTH, content=bt) popup.part_text_set("title,text", "Title") bt = Button(win, text="OK") popup.part_content_set("button1", bt) bt = Button(win, text="Cancel") popup.part_content_set("button2", bt) bt = Button(win, text="Close") bt.callback_clicked_add(cb_bnt_close, popup) popup.part_content_set("button3", bt) popup.show()
def cb_popup_center_text_1button_hide_show(li, item, win): global times global g_popup times += 1 if g_popup is not None: g_popup.text = "You have checked this popup %d times." % times g_popup.show() return g_popup = Popup(win, size_hint_weight=EXPAND_BOTH) g_popup.text = "Hide this popup by using the button." \ "When you click list item again, you will see this popup again." bt = Button(win, text="Hide") bt.callback_clicked_add(lambda b: g_popup.hide()) g_popup.part_content_set("button1", bt) g_popup.show()
def safe_quit(self): if need_save() is False: elm.exit() else: pp = Popup(self, text="You have unsave changes, if you don't save now all your recent modification will be lost.") pp.part_text_set('title,text', 'Save changes to your txt file?') btn = Button(pp, text='Close without saving') btn.callback_clicked_add(lambda b: elm.exit()) pp.part_content_set('button1', btn) btn = Button(pp, text='Cancel') btn.callback_clicked_add(lambda b: pp.delete()) pp.part_content_set('button2', btn) btn = Button(pp, text='Save') btn.callback_clicked_add(lambda b: self.save(True)) pp.part_content_set('button3', btn) pp.show()
def cb_popup_center_title_item_3button(li, item, win): popup = Popup(win, size_hint_weight=EXPAND_BOTH) popup.part_text_set("title,text", "Title") for i in range(1, 11): if i in [3, 5, 6]: ic = Icon(win, file=os.path.join(img_path, "logo_small.png")) popup.item_append("item"+str(i), ic) else: popup.item_append("item"+str(i), None) bt = Button(win, text="OK") popup.part_content_set("button1", bt) bt = Button(win, text="Cancel") popup.part_content_set("button2", bt) bt = Button(win, text="Close") bt.callback_clicked_add(cb_bnt_close, popup) popup.part_content_set("button3", bt) popup.show()
def cb_popup_bottom_title_text_3button(li, item, win): popup = Popup(win, size_hint_weight=EXPAND_BOTH, content_text_wrap_type=ELM_WRAP_CHAR) popup.text = "This Popup has title area, content area and " \ "action area set with content being character wrapped. " \ "action area has three buttons OK, Cancel and Close" popup.part_text_set("title,text", "Title") ic = Icon(win, file=os.path.join(img_path, "logo_small.png")) popup.part_content_set("title,icon", ic) bt = Button(win, text="OK") popup.part_content_set("button1", bt) bt = Button(win, text="Cancel") popup.part_content_set("button2", bt) bt = Button(win, text="Close") bt.callback_clicked_add(cb_bnt_close, popup) popup.part_content_set("button3", bt) popup.show()
def _file_change(self): # hack to make popup respect min_size rect = Rectangle(self.parent.evas, size_hint_min=(400,400)) tb = Table(self.parent) tb.pack(rect, 0, 0, 1, 1) # show the fileselector inside a popup popup = Popup(self.top_widget, content=tb) popup.part_text_set('title,text', 'Choose the Todo.txt file to use') popup.show() # the fileselector widget fs = Fileselector(popup, is_save=False, expandable=False, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) fs.callback_activated_add(self._file_change_done, popup) fs.callback_done_add(self._file_change_done, popup) try: fs.selected = options.txt_file except: fs.path = os.path.expanduser('~') fs.show() tb.pack(fs, 0, 0, 1, 1)
class FolderSelector(Fileselector): def __init__(self, parent): Fileselector.__init__(self, parent, is_save=False, folder_only=True, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.path = os.getcwd() # table+rect to respect min size :/ tb = Table(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) r = Rectangle(self.evas, color=(0,0,0,0), size_hint_min=(300,300), size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) tb.pack(r, 0, 0, 1, 1) tb.pack(self, 0, 0, 1, 1) self.popup = Popup(parent) self.popup.part_text_set('title,text', 'Choose repository') self.popup.content = tb self.popup.show() self.show() def delete(self): self.popup.delete()
def cb_popup_center_title_item_3button(li, item, win): popup = Popup(win, size_hint_weight=EXPAND_BOTH) popup.part_text_set("title,text", "Title") for i in range(1, 11): if i in [3, 5, 6]: ic = Icon(win, file=os.path.join(img_path, "logo_small.png")) popup.item_append("item" + str(i), ic) else: popup.item_append("item" + str(i), None) bt = Button(win, text="OK") popup.part_content_set("button1", bt) bt = Button(win, text="Cancel") popup.part_content_set("button2", bt) bt = Button(win, text="Close") bt.callback_clicked_add(cb_bnt_close, popup) popup.part_content_set("button3", bt) popup.show()
def ask_what_to_do_next(self): pop = Popup(self) pop.part_text_set('title,text', _('Extract completed')) box = Box(pop) pop.content = box box.show() lb = Label(pop, text=_('What to do next?'), size_hint_align=FILL_HORIZ) box.pack_end(lb) lb.show() btn = Button(pop, text=_('Open Filemanager'), size_hint_align=FILL_HORIZ) btn.callback_clicked_add(self._open_fm_and_exit_cb) box.pack_end(btn) btn.show() btn = Button(pop, text=_('Open Terminal'), size_hint_align=FILL_HORIZ) btn.callback_clicked_add(self._open_term_and_exit_cb) box.pack_end(btn) btn.show() btn = Button(pop, text=_('Close this popup'), size_hint_align=FILL_HORIZ) btn.callback_clicked_add(lambda b: pop.delete()) box.pack_end(btn) btn.show() btn = Button(pop, text=_('Exit'), size_hint_align=FILL_HORIZ) btn.callback_clicked_add(lambda b: self.app.exit()) box.pack_end(btn) btn.show() pop.show()
def _popup_build(self): popup = Popup(self.top_widget) popup.part_text_set('title,text', 'Choose the color for %s' % self._tag_name) popup.callback_block_clicked_add(lambda p: popup.delete()) cs = Colorselector(popup, color=self._rect.color) cs.callback_changed_add(lambda s: setattr(rect, 'color', cs.color)) popup.content = cs rect = Rectangle(popup.evas, color=self._rect.color) frame = Frame(popup, style='pad_small', content=rect) popup.part_content_set('button1', frame) bt = Button(popup, text='Accept') bt.callback_clicked_add(self._popup_accept_cb, popup, cs) popup.part_content_set('button2', bt) bt = Button(popup, text='Cancel') bt.callback_clicked_add(lambda b: popup.delete()) popup.part_content_set('button3', bt) popup.show()
def item_selected_cb(self, gl, item): name = item.data if item.parent is self.activatable_group: # activate the service, async with a cool popup bus.call_async("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "StartServiceByName", "su", (name, 0), None, None) spinner = Progressbar(self.win, style="wheel", pulse_mode=True) spinner.pulse(True) def stop_waiting_cb(btn): self.waiting_popup.delete() self.waiting_activation = None button = Button(self.win, text="Stop waiting") button.callback_clicked_add(stop_waiting_cb) popup = Popup(self.win, content=spinner) popup.part_text_set('title,text', 'Activating service...') popup.part_content_set('button1', button) popup.show() self.waiting_activation = name self.waiting_popup = popup else: self.win.detail_list.populate(name)
def _task_edit_start(self, task): pp = Popup(self.top_widget) pp.part_text_set('title,text', 'Edit task') en = Entry(pp, editable=True, single_line=True, scrollable=True, text=task.raw_txt) en.callback_activated_add(lambda e: self._task_edit_end(task, en, pp)) en.callback_aborted_add(lambda e: pp.delete()) pp.part_content_set('default', en) b = Button(pp, text='Cancel') b.callback_clicked_add(lambda b: pp.delete()) pp.part_content_set('button1', b) b = Button(pp, text='Accept') b.callback_clicked_add(lambda b: self._task_edit_end(task, en, pp)) pp.part_content_set('button2', b) pp.show() en.cursor_begin_set() en.cursor_selection_begin() en.cursor_end_set() en.cursor_selection_end()
def popup(self, tb, it): msg = Popup(self.win, size_hint_weight=EXPAND_BOTH, text="Save Clicked") msg.callback_block_clicked_add(self.closePopup) msg.show() it.selected_set(False)
class FileSelector(Box): '''FileSelector Class''' # pylint: disable=too-many-instance-attributes, too-many-statements def __init__(self, parent_widget, *args, default_path='', default_populate=True, **kwargs): Box.__init__(self, parent_widget, *args, **kwargs) self.cancel_cb = None self.action_cb = None self.cb_dir_change = None self.threaded_fn = ThreadedFunction() # pylint: disable=c-extension-no-member self._timer = ecore.Timer(0.02, self.populate_file) # Watch key presses for ctrl+l to select entry parent_widget.elm_event_callback_add(self.cb_events) self.selected_dir = None self.show_hidden = False self.cur_dir = None self.focused_entry = None self.dir_only = False self.sort_reverse = False self.adding_hidden = False self.pending_files = deque() self.cur_subdirs = [] self.cur_files = [] # Mode should be 'save' or 'load' self.mode = 'save' self.home = os.path.expanduser('~') desktop = os.environ.get('XDG_DESKTOP_DIR') if desktop: self.desktop = desktop else: self.desktop = self.home + '/Desktop' self.root = '/' # Label+Entry for File Name self.filename_bx = Box(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ) self.filename_bx.horizontal = True self.filename_bx.show() file_label = Label(self, size_hint_weight=(0.15, EVAS_HINT_EXPAND), size_hint_align=FILL_HORIZ) file_label.text = 'Filename:' file_label.show() self.file_entry = Entry(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_HORIZ) self.file_entry.single_line_set(True) self.file_entry.scrollable_set(True) self.file_entry.callback_changed_user_add(self.cb_file_entry) self.file_entry.show() self.filename_bx.pack_end(file_label) self.filename_bx.pack_end(self.file_entry) sep = Separator(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ) sep.horizontal_set(True) sep.show() # Label+Entry for File Path self.filepath_bx = Box(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ) self.filepath_bx.horizontal = True self.filepath_bx.show() file_label = Label(self, size_hint_weight=(0.15, EVAS_HINT_EXPAND), size_hint_align=FILL_HORIZ) file_label.text = 'Current Folder:' file_label.show() self.filepath_en = Entry(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_HORIZ) self.filepath_en.single_line_set(True) self.filepath_en.scrollable_set(True) self.filepath_en.callback_changed_user_add(self.cb_file_entry) self.filepath_en.callback_unfocused_add(self.cb_filepath_en) self.filepath_en.callback_activated_add(self.cb_filepath_en) # Wish this worked. Doesn't seem to do anything # Working now EFL 1.22 ? self.filepath_en.input_hint_set(ELM_INPUT_HINT_AUTO_COMPLETE) if default_path and os.path.isdir(default_path): start = default_path else: start = self.home self.filepath_en.show() self.filepath_bx.pack_end(file_label) self.filepath_bx.pack_end(self.filepath_en) self.autocomplete_hover = Hoversel(self, hover_parent=self) self.autocomplete_hover.callback_selected_add(self.cb_hover) self.autocomplete_hover.show() self.file_selector_bx = Panes(self, content_left_size=0.3, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.file_selector_bx.show() # Bookmarks Box contains: # # - Button - Up Arrow # - List - Home/Desktop/Root/GTK bookmarks # - Box # -- Button - Add Bookmark # -- Button - Remove Bookmark self.bookmark_bx = Box(self, size_hint_weight=(0.3, EVAS_HINT_EXPAND), size_hint_align=FILL_BOTH) self.bookmark_bx.show() up_ic = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH, order_lookup=ELM_ICON_LOOKUP_THEME) up_ic.standard_set('arrow-up') up_ic.show() self.up_btn = Button(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ, content=up_ic) self.up_btn.text = 'Up' self.up_btn.callback_pressed_add(self.cb_up_btn) self.up_btn.show() self.bookmarks_lst = List(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.bookmarks_lst.callback_activated_add(self.cb_bookmarks_lst) self.bookmarks_lst.show() self.bookmark_modbox = Box(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ) self.bookmark_modbox.horizontal = True self.bookmark_modbox.show() con = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) con.standard_set('list-add') con.show() self.add_btn = Button(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ, content=con) self.add_btn.callback_pressed_add(self.cb_add_btn) self.add_btn.disabled = True self.add_btn.show() con = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) con.standard_set('list-remove') con.show() self.rm_btn = Button(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ, content=con) self.rm_btn.callback_pressed_add(self.cb_remove) self.rm_btn.disabled = True self.rm_btn.show() self.bookmark_modbox.pack_end(self.add_btn) self.bookmark_modbox.pack_end(self.rm_btn) self.bookmark_bx.pack_end(self.up_btn) self.bookmark_bx.pack_end(self.bookmarks_lst) self.bookmark_bx.pack_end(self.bookmark_modbox) # Directory List self.file_list_bx = Box(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.file_list_bx.show() self.file_sort_btn = Button(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ) self.file_sort_btn.text = u'⬆ Name' self.file_sort_btn.callback_pressed_add(self.cb_sort) self.file_sort_btn.show() self.file_lst = Genlist(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH, homogeneous=True, mode=ELM_LIST_COMPRESS) self.file_lst.callback_activated_add(self.cb_file_lst) self.file_lst.show() self.preview = preview = Image(self) preview.size_hint_align = FILL_BOTH preview.show() self.file_list_bx.pack_end(self.file_sort_btn) self.file_list_bx.pack_end(self.file_lst) self.file_list_bx.pack_end(self.preview) self.file_selector_bx.part_content_set('left', self.bookmark_bx) self.file_selector_bx.part_content_set('right', self.file_list_bx) # Cancel and Save/Open button self.button_bx = Box(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=(1.0, 0.5)) self.button_bx.horizontal = True self.button_bx.show() self.action_ic = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.action_ic.standard_set('document-save') self.action_ic.show() self.action_btn = Button(self, size_hint_weight=(0.0, 0.0), size_hint_align=(1.0, 0.5), content=self.action_ic) self.action_btn.text = 'Save ' self.action_btn.callback_pressed_add(self.cb_action_btn) self.action_btn.show() cancel_ic = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) cancel_ic.standard_set('application-exit') cancel_ic.show() self.cancel_btn = Button(self, size_hint_weight=(0.0, 0.0), size_hint_align=(1.0, 0.5), content=cancel_ic) self.cancel_btn.text = 'Cancel ' self.cancel_btn.callback_pressed_add(self.cb_cancel_btn) self.cancel_btn.show() con = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) con.standard_set('edit-find') con.show() self.hidden_btn = Button(self, size_hint_weight=(0.0, 0.0), size_hint_align=(1.0, 0.5), content=con) self.hidden_btn.text = 'Toggle Hidden ' self.hidden_btn.callback_pressed_add(self.cb_toggle_hidden) self.hidden_btn.show() con = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) con.standard_set('folder-new') con.show() self.create_dir_btn = Button(self, size_hint_weight=(0.0, 0.0), size_hint_align=(1.0, 0.5), content=con) self.create_dir_btn.text = 'Create Folder ' self.create_dir_btn.callback_pressed_add(self.cb_create_dir) self.create_dir_btn.show() self.button_bx.pack_end(self.create_dir_btn) self.button_bx.pack_end(self.hidden_btn) self.button_bx.pack_end(self.cancel_btn) self.button_bx.pack_end(self.action_btn) self.pack_end(self.filename_bx) self.pack_end(sep) self.pack_end(self.filepath_bx) self.pack_end(self.autocomplete_hover) self.pack_end(self.file_selector_bx) self.pack_end(self.button_bx) self.populate_bookmarks() self.create_popup = Popup(self) self.create_popup.part_text_set('title,text', 'Create Folder:') self.create_en = Entry(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ) self.create_en.single_line_set(True) self.create_en.scrollable_set(True) self.create_en.show() self.create_popup.content = self.create_en bt0 = Button(self, text='Create') bt0.callback_clicked_add(self.cb_create_folder) self.create_popup.part_content_set('button1', bt0) bt1 = Button(self, text='Cancel') bt1.callback_clicked_add(self.cb_close_popup) self.create_popup.part_content_set('button2', bt1) self.recent = None # keeps pylint happy: if default_populate: self.populate_files(start) def dir_only_set(self, value): '''Set folder only attribute and adjust display''' self.dir_only = value if not self.dir_only: self.filename_bx.show() else: self.filename_bx.hide() def cb_create_folder(self, obj): '''Create a new folder''' new = f'{self.cur_dir}{self.create_en.text}' os.makedirs(new) self.cb_close_popup() self.populate_files(self.cur_dir) def cb_create_dir(self, obj): '''Open popup to create a new folder''' self.create_en.text = '' self.create_popup.show() self.create_en.select_all() def cb_close_popup(self, btn=None): '''Close popup''' self.create_popup.hide() # pylint: disable=unused-argument def shutdown(self, obj=None): '''Cleanup function for FileSelector widget shutdown''' self._timer.delete() self.threaded_fn.shutdown() def cb_sort(self, btn): '''callback for sort button''' self.sort_reverse = not self.sort_reverse if self.sort_reverse: self.file_sort_btn.text = u'⬇ Name' else: self.file_sort_btn.text = u'⬆ Name' self.populate_files(self.cur_dir) def populate_bookmarks(self): '''Fill Bookamrks List''' con = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) con.standard_set('document-open-recent') con.show() cur_item = self.bookmarks_lst.item_append('Recent', icon=con) cur_item.data['path'] = 'recent:///' cur_item = self.bookmarks_lst.item_append('') cur_item.separator_set(True) con = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) con.standard_set('user-home') con.show() cur_item = self.bookmarks_lst.item_append('Home', icon=con) cur_item.data['path'] = self.home if os.path.isdir(self.desktop): con = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) con.standard_set('user-desktop') con.show() cur_item = self.bookmarks_lst.item_append('Desktop', icon=con) cur_item.data['path'] = self.desktop con = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) con.standard_set('drive-harddisk') con.show() cur_item = self.bookmarks_lst.item_append('Root', icon=con) cur_item.data['path'] = self.root cur_item = self.bookmarks_lst.item_append('') cur_item.separator_set(True) for url in self.get_gtk_bookmarks(): con = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) con.standard_set('folder') con.show() cur_item = self.bookmarks_lst.item_append(url.split('/')[-1], icon=con) cur_item.data['path'] = url[7:] def populate_file(self): '''Add Pending File to Files list''' pen_file = len(self.pending_files) if pen_file: for _ in range(int(math.sqrt(pen_file))): path, name, is_dir = self.pending_files.popleft() self.pack_all(path, name, is_dir) # else: # self._timer.freeze() return True def populate_files(self, path): '''Start threaded FN to get dir contents''' self.autocomplete_hover.hover_end() self.pending_files.clear() if path[:-1] != '/': path = path + '/' if path != self.filepath_en.text or not self.show_hidden: self.adding_hidden = False if self.cb_dir_change: self.cb_dir_change(path) del self.cur_subdirs[:] del self.cur_files[:] self.file_lst.clear() else: self.adding_hidden = True self.filepath_en.text = path.replace('//', '/') self.cur_dir = path.replace('//', '/') self.threaded_fn.run(self.get_dir_contents) def get_dir_contents(self): '''Add Folder contents to pending files''' path = self.cur_dir if path == 'recent://': self.recent = Bookmarks() data = list(self.recent.dict.keys()) for cur in data: self.pending_files.append([path, cur, False]) return data = os.listdir(str(path)) sorted_data = [] for name in data: is_dir = os.path.isdir(f'{path}{name}') if is_dir: self.cur_subdirs.append(name) if self.sort_reverse: sorted_data.append([1, name]) else: sorted_data.append([0, name]) else: self.cur_files.append(name) if self.sort_reverse: sorted_data.append([0, name]) else: sorted_data.append([1, name]) sorted_data.sort(reverse=self.sort_reverse) for cur in sorted_data: name = cur[1] is_dir = cur[0] if self.sort_reverse else not cur[0] if self.adding_hidden and name[0] == '.': self.pending_files.append([path, name, is_dir]) elif (name[0] != '.' or self.show_hidden) and not self.adding_hidden: self.pending_files.append([path, name, is_dir]) def pack_all(self, path, name, is_dir): '''Append to genlist''' if is_dir: gen_lst_it = GenlistItem(item_data={ 'type': 'dir', 'path': path, 'd': name }, item_class=DIRGLIC, func=self.list_it_selected) else: gen_lst_it = GenlistItem(item_data={ 'type': 'file', 'path': path, 'd': name }, item_class=FILEGLIC, func=self.list_it_selected) gen_lst_it.append_to(self.file_lst) def cb_file_lst(self, obj, item=None, event=None): '''File list double clicked callback''' if item.data['type'] == 'dir': self.add_btn.disabled = True self.rm_btn.disabled = True self.populate_files(item.data['path'] + item.text) else: self.cb_action_btn(self.action_btn) # pylint: disable=no-self-use def get_gtk_bookmarks(self): '''Read GTK bookmarks''' try: with open(os.path.expanduser('~/.config/gtk-3.0/bookmarks'), 'r') as gtk_bk: bks = [] for url in gtk_bk: url = url.split(' ')[0] url = url.replace('%20', ' ') url = url.strip() bks.append(url) return bks except IOError: return [] def cb_bookmarks_lst(self, obj, item=None, event=None): '''Bookamrk list item double clicked callback''' item.selected_set(False) self.add_btn.disabled = True self.rm_btn.disabled = True self.populate_files(item.data['path']) def list_it_selected(self, item, gen_lst, data): '''Genlist item selected''' if item.data['type'] == 'dir': self.dir_selected(item) else: self.file_selected(item.text) item.selected_set(False) def file_selected(self, cur): '''File was selected, update everything''' self.file_entry.text = cur self.add_btn.disabled = True self.rm_btn.disabled = True self.selected_dir = None # Update image preview if an image is selected if cur[-3:] in ['jpg', 'png', 'gif']: if self.filepath_en.text == 'recent://': self.preview.file_set(self.recent[cur]) else: self.preview.file_set(f'{self.filepath_en.text}/{cur}') self.preview.size_hint_weight = (1.0, 0.4) else: self.preview.size_hint_weight = (0, 0) def dir_selected(self, btn): '''Folder was selected, update everything''' cur = btn.data['path'] if btn == self.selected_dir: self.populate_files(cur) self.add_btn.disabled = True else: self.selected_dir = btn gtk_bks = self.get_gtk_bookmarks() to_append = f'file://{self.filepath_en.text}{self.selected_dir.text}' if to_append not in gtk_bks: self.add_btn.disabled = False self.rm_btn.disabled = True else: self.add_btn.disabled = True self.rm_btn.disabled = False def cb_up_btn(self, btn): '''Callback for dir up button''' cur = self.filepath_en.text.split('/') del cur[-1] del cur[-1] self.populate_files('/'.join(cur)) def cb_add_btn(self, btn): '''Add dir button pressed''' safe = self.selected_dir.text.replace(' ', '%20') cur = f"file://{self.filepath_en.text}{safe}" con = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) con.standard_set('gtk-directory') con.show() current = self.bookmarks_lst.item_append(self.selected_dir.text, icon=con) current.data[ 'path'] = f'{self.filepath_en.text}{self.selected_dir.text}' self.bookmarks_lst.go() self.add_btn.disabled = True self.rm_btn.disabled = False with open(os.path.expanduser('~/.config/gtk-3.0/bookmarks'), 'a') as gtk_bk: gtk_bk.write(cur + ' ' + self.selected_dir.text + '\n') def cb_remove(self, btn): '''Remove button pressed callback''' cur = f'file://{self.filepath_en.text}{self.selected_dir.text}' bks = self.get_gtk_bookmarks() bks.remove(cur) with open(os.path.expanduser('~/.config/gtk-3.0/bookmarks'), 'w') as gtk_bk: for url in bks: name = url.split('/')[-1] url = url.replace(' ', '%20') gtk_bk.write(url + ' ' + name + '\n') self.bookmarks_lst.clear() self.populate_bookmarks() self.add_btn.disabled = False self.rm_btn.disabled = True def set_mode(self, mode): '''Set FileSelector mode: save or open''' self.mode = mode.lower() self.action_btn.text = f'{mode} ' self.action_ic.standard_set(f'document-{mode.lower()}') if self.mode != 'save': self.create_dir_btn.hide() else: self.create_dir_btn.show() def cb_events(self, obj, src, event_type, event): '''Keyboard event callback: Watch key presses for ctrl+l to select entry''' if event.modifier_is_set( 'Control') and event_type == EVAS_CALLBACK_KEY_DOWN: if event.key.lower() == 'l': self.filepath_en.focus_set(True) self.filepath_en.cursor_end_set() def cb_toggle_hidden(self, btn): '''Toggle hidden files and folders''' self.show_hidden = not self.show_hidden self.populate_files(self.filepath_en.text) def callback_cancel_add(self, callback): '''Add a cancel callback''' self.cancel_cb = callback def callback_activated_add(self, callback): '''Add an action callback''' self.action_cb = callback def callback_directory_open_add(self, callback): '''Add an open folder callback''' self.cb_dir_change = callback def cb_cancel_btn(self, btn): '''Cancel button callback''' if self.cancel_cb: self.cancel_cb(self) def cb_action_btn(self, btn): '''Action button callback''' if self.action_cb: if not self.dir_only and self.file_entry.text: if self.filepath_en.text == 'recent://': self.action_cb(self, self.recent[self.file_entry.text]) else: self.action_cb( self, f'{self.filepath_en.text}{self.file_entry.text}') elif self.dir_only: self.action_cb(self, f'{self.filepath_en.text}') def cb_file_entry(self, entry): '''File entry callback''' typed = entry.text.split('/')[-1] new_lst = [] self.focused_entry = entry if entry == self.filepath_en: for name in self.cur_subdirs: if typed in name: if len(new_lst) < 10: new_lst.append(name) else: break else: for name in self.cur_files: if typed in name: if len(new_lst) < 10: new_lst.append(name) else: break if self.autocomplete_hover.expanded_get(): self.autocomplete_hover.hover_end() self.autocomplete_hover.clear() for name in new_lst: self.autocomplete_hover.item_add(name) self.autocomplete_hover.hover_begin() self.focused_entry.focus = True def cb_hover(self, hov, item): '''Autocomplete Hover item selected callback''' hov.hover_end() if self.focused_entry == self.filepath_en: self.populate_files(f'{self.cur_dir}{item.text}') self.filepath_en.cursor_end_set() else: self.file_entry.text = item.text self.file_entry.cursor_end_set() def cb_filepath_en(self, entry): '''File Path Entry callback''' if os.path.isdir(entry.text) and entry.text != self.cur_dir: self.populate_files(entry.text) self.filepath_en.cursor_end_set() else: # entry.text = self.cur_dir pass def selected_get(self): '''Return selected''' return f'{self.filepath_en.text}{self.file_entry.text}'
class Interface(object): def __init__( self ): self.mainWindow = StandardWindow("epad", "Untitled - ePad", size=(600, 400)) self.mainWindow.callback_delete_request_add(self.closeChecks) self.mainWindow.elm_event_callback_add(self.eventsCb) icon = Icon(self.mainWindow) icon.size_hint_weight_set(EVAS_HINT_EXPAND, EVAS_HINT_EXPAND) icon.size_hint_align_set(EVAS_HINT_FILL, EVAS_HINT_FILL) icon.standard_set('accessories-text-editor') # assumes image icon is in local dir, may need to change later icon.show() self.mainWindow.icon_object_set(icon.object_get()) self.mainBox = Box(self.mainWindow, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.mainBox.show() self.mainTb = Toolbar(self.mainWindow, homogeneous=False, size_hint_weight=(0.0, 0.0), size_hint_align=(EVAS_HINT_FILL, 0.0)) self.mainTb.menu_parent = self.mainWindow self.mainTb.item_append("document-new", "New", self.newPress) self.mainTb.item_append("document-open", "Open", self.openPress) self.mainTb.item_append("document-save", "Save", self.savePress) self.mainTb.item_append("document-save-as", "Save As", self.saveAsPress) # -- Edit Dropdown Menu -- tb_it = self.mainTb.item_append("edit", "Edit") tb_it.menu = True menu = tb_it.menu menu.item_add(None, "Copy", "edit-copy", self.copyPress) menu.item_add(None, "Paste", "edit-paste", self.pastePress) menu.item_add(None, "Cut", "edit-cut", self.cutPress) menu.item_separator_add() menu.item_add(None, "Select All", "edit-select-all", self.selectAllPress) # ----------------------- # self.mainTb.item_append("settings", "Options", self.optionsPress) self.mainTb.item_append("dialog-information", "About", self.aboutPress) self.mainEn = Entry(self.mainWindow, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.mainEn.callback_changed_user_add(self.textEdited) self.mainEn.scrollable_set(True) # creates scrollbars rather than enlarge window self.mainEn.line_wrap_set(False) # does not allow line wrap (can be changed by user) self.mainEn.autosave_set(False) # set to false to reduce disk I/O self.mainEn.elm_event_callback_add(self.eventsCb) self.mainEn.markup_filter_append(self.textFilter) self.mainEn.show() self.mainTb.show() self.mainBox.pack_end(self.mainTb) self.mainBox.pack_end(self.mainEn) #Build our file selector for saving/loading files self.fileBox = Box(self.mainWindow, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.fileBox.show() self.fileLabel = Label(self.mainWindow, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_BOTH) self.fileLabel.text = "" self.fileLabel.show() self.fileSelector = Fileselector(self.mainWindow, is_save=False, expandable=False, folder_only=False, path=os.getenv("HOME"), size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.fileSelector.callback_done_add(self.fileSelected) #self.fileSelector.callback_selected_add(fs_cb_selected, win) #self.fileSelector.callback_directory_open_add(fs_cb_directory_open, win) self.fileSelector.show() self.fileBox.pack_end(self.fileLabel) self.fileBox.pack_end(self.fileSelector) # the flip object has the file selector on one side and the GUI on the other self.flip = Flip(self.mainWindow, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.flip.part_content_set("front", self.mainBox) self.flip.part_content_set("back", self.fileBox) self.mainWindow.resize_object_add(self.flip) self.flip.show() self.isSaved = True self.isNewFile = False self.confirmPopup = None def newPress( self, obj, it ): self.newFile() it.selected_set(False) def openPress( self, obj, it ): self.openFile() it.selected_set(False) def savePress( self, obj, it ): self.saveFile() it.selected_set(False) def saveAsPress( self, obj, it ): self.saveAs() it.selected_set(False) def optionsPress( self, obj, it ): it.selected_set(False) def copyPress( self, obj, it ): self.mainEn.selection_copy() it.selected_set(False) def pastePress( self, obj, it ): self.mainEn.selection_paste() it.selected_set(False) def cutPress( self, obj, it ): self.mainEn.selection_cut() it.selected_set(False) def selectAllPress( self, obj, it ): self.mainEn.select_all() it.selected_set(False) def textEdited( self, obj ): ourFile = self.mainEn.file_get()[0] if ourFile and not self.isNewFile: self.mainWindow.title_set("*%s - ePad"%self.mainEn.file_get()[0].split("/")[len(self.mainEn.file_get()[0].split("/"))-1]) else: self.mainWindow.title_set("*Untitlted - ePad") self.isSaved = False def fileSelected( self, fs, file_selected, onStartup=False ): if not onStartup: self.flip.go(ELM_FLIP_INTERACTION_ROTATE) print(file_selected) IsSave = fs.is_save_get() if file_selected: if IsSave: newfile = open(file_selected,'w') # creates new file tmp_text = self.mainEn.entry_get() newfile.write(tmp_text) newfile.close() self.mainEn.file_set(file_selected, ELM_TEXT_FORMAT_PLAIN_UTF8) self.mainEn.entry_set(tmp_text) self.mainEn.file_save() self.mainWindow.title_set("%s - ePad" % file_selected.split("/")[len(file_selected.split("/"))-1]) self.isSaved = True self.isNewFile = False else: try: self.mainEn.file_set(file_selected, ELM_TEXT_FORMAT_PLAIN_UTF8) except RuntimeError: print("Empty file: {0}".format(file_selected)) self.mainWindow.title_set("%s - ePad" % file_selected.split("/")[len(file_selected.split("/"))-1]) def aboutPress( self, obj, it ): #About popup self.popupAbout = Popup(self.mainWindow, size_hint_weight=EXPAND_BOTH) self.popupAbout.text = "ePad - A simple text editor written in python and elementary<br><br> " \ "By: Jeff Hoogland" bt = Button(self.mainWindow, text="Done") bt.callback_clicked_add(self.aboutClose) self.popupAbout.part_content_set("button1", bt) self.popupAbout.show() it.selected_set(False) def aboutClose( self, bt ): self.popupAbout.delete() def newFile( self , obj=None, ignoreSave=False ): if self.isSaved == True or ignoreSave == True: trans = Transit() trans.object_add(self.mainEn) trans.auto_reverse = True trans.effect_wipe_add( ELM_TRANSIT_EFFECT_WIPE_TYPE_HIDE, ELM_TRANSIT_EFFECT_WIPE_DIR_RIGHT) trans.duration = 0.5 trans.go() time.sleep(0.5) self.mainWindow.title_set("Untitlted - ePad") self.mainEn.delete() self.mainEn = Entry(self.mainWindow, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.mainEn.callback_changed_user_add(self.textEdited) self.mainEn.scrollable_set(True) # creates scrollbars rather than enlarge window self.mainEn.line_wrap_set(False) # does not allow line wrap (can be changed by user) self.mainEn.autosave_set(False) # set to false to reduce disk I/O self.mainEn.elm_event_callback_add(self.eventsCb) self.mainEn.markup_filter_append(self.textFilter) self.mainEn.show() self.mainBox.pack_end(self.mainEn) self.isNewFile = True elif self.confirmPopup == None: self.confirmSave(self.newFile) def openFile( self, obj=None, ignoreSave=False ): if self.isSaved == True or ignoreSave == True: self.fileSelector.is_save_set(False) self.fileLabel.text = "<b>Select a text file to open:</b>" self.flip.go(ELM_FLIP_ROTATE_YZ_CENTER_AXIS) elif self.confirmPopup == None: self.confirmSave(self.openFile) def confirmSave( self, ourCallback=None ): self.confirmPopup = Popup(self.mainWindow, size_hint_weight=EXPAND_BOTH) self.confirmPopup.part_text_set("title,text","File Unsaved") if self.mainEn.file_get()[0]: self.confirmPopup.text = "Save changes to '%s'?" % self.mainEn.file_get()[0].split("/")[len(self.mainEn.file_get()[0].split("/"))-1] else: self.confirmPopup.text = "Save changes to 'Untitlted'?" # Close without saving button no_btt = Button(self.mainWindow) no_btt.text = "No" no_btt.callback_clicked_add(self.closePopup, self.confirmPopup) if ourCallback is not None: no_btt.callback_clicked_add(ourCallback, True) no_btt.show() # cancel close request cancel_btt = Button(self.mainWindow) cancel_btt.text = "Cancel" cancel_btt.callback_clicked_add(self.closePopup, self.confirmPopup) cancel_btt.show() # Save the file and then close button sav_btt = Button(self.mainWindow) sav_btt.text = "Yes" sav_btt.callback_clicked_add(self.saveFile) sav_btt.callback_clicked_add(self.closePopup, self.confirmPopup) sav_btt.show() # add buttons to popup self.confirmPopup.part_content_set("button1", no_btt) self.confirmPopup.part_content_set("button2", cancel_btt) self.confirmPopup.part_content_set("button3", sav_btt) self.confirmPopup.show() def saveAs( self ): self.fileSelector.is_save_set(True) self.fileLabel.text = "<b>Save new file to where:</b>" self.flip.go(ELM_FLIP_ROTATE_XZ_CENTER_AXIS) def saveFile( self, obj=False ): if self.mainEn.file_get()[0] == None or self.isNewFile: self.saveAs() else: self.mainEn.file_save() self.mainWindow.title_set("%s - ePad"%self.mainEn.file_get()[0].split("/")[len(self.mainEn.file_get()[0].split("/"))-1]) self.isSaved = True def closeChecks( self, obj ): print(self.isSaved) if self.isSaved == False and self.confirmPopup == None: self.confirmSave(self.closeApp) else: self.closeApp() def closePopup( self, bt, confirmPopup ): self.confirmPopup.delete() self.confirmPopup = None def closeApp( self, obj=False, trash=False ): elementary.exit() def eventsCb( self, obj, src, event_type, event ): #print event_type #print event.key #print "Control Key Status: %s" %event.modifier_is_set("Control") #print "Shift Key Status: %s" %event.modifier_is_set("Shift") #print event.modifier_is_set("Alt") if event.modifier_is_set("Control"): if event.key.lower() == "n": self.newFile() elif event.key.lower() == "s" and event.modifier_is_set("Shift"): self.saveAs() elif event.key.lower() == "s": self.saveFile() elif event.key.lower() == "o": self.openFile() def textFilter( self, obj, theText, data ): #print theText #Block ctrl+hot keys if theText == "" or theText == "" or theText == "": return None else: return theText def launch( self, startingFile=False ): if startingFile: self.fileSelected(self.fileSelector, startingFile, True) self.mainWindow.show()
class aboutWin(Window): def __init__(self, parent, canvas): self._parent = parent self._canvas = canvas # Dialog Window Basics self.aboutDialog = Window("epad", ELM_WIN_DIALOG_BASIC) # self.aboutDialog.callback_delete_request_add(self.closeabout) # Set Dialog background background = Background(self.aboutDialog, size_hint_weight=EXPAND_BOTH) self.aboutDialog.resize_object_add(background) background.show() # mainBox = Box(self.aboutDialog, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.aboutDialog.resize_object_add(mainBox) mainBox.show() # need_ethumb() icon = Icon(self.aboutDialog, thumb='True') icon.standard_set('accessories-text-editor') # Using gksudo or sudo fails to load Image here # unless options specify using preserving their existing environment. # may also fail to load other icons but does not raise an exception # in that situation. # Works fine using eSudo as a gksudo alternative, # other alternatives not tested try: aboutImage = Image(self.aboutDialog, no_scale=True, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH, file=icon.file_get()) aboutImage.aspect_fixed_set(False) mainBox.pack_end(aboutImage) aboutImage.show() except RuntimeError as msg: print("Warning: to run as root please use:\n" "\t gksudo -k or sudo -E \n" "Continuing with minor errors ...") labelBox = Box(self.aboutDialog, size_hint_weight=EXPAND_NONE) mainBox.pack_end(labelBox) labelBox.show() # Entry to hold text titleStr = '<br>ePad version <em>{0}</em><br>'.format(__version__) aboutStr = ('<br>A simple text editor written in <br>' 'python and elementary<br>') aboutLbTitle = Label(self.aboutDialog, style='marker') aboutLbTitle.text = titleStr aboutLbTitle.show() labelBox.pack_end(aboutLbTitle) sep = Separator(self.aboutDialog, horizontal=True) labelBox.pack_end(sep) sep.show() aboutText = Label(self.aboutDialog) aboutText.text = aboutStr aboutText.show() labelBox.pack_end(aboutText) aboutCopyright = Label(self.aboutDialog) aboutCopyright.text = '<b>Copyright</b> © <i>2014 Bodhi Linux</i><br>' aboutCopyright.show() labelBox.pack_end(aboutCopyright) # Dialog Buttons # Horizontal Box for Dialog Buttons buttonBox = Box(self.aboutDialog, horizontal=True, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_BOTH, padding=PADDING) buttonBox.size_hint_weight_set(EVAS_HINT_EXPAND, 0.0) buttonBox.show() labelBox.pack_end(buttonBox) # Credits Button creditsBtn = Button(self.aboutDialog, text="Credits ", size_hint_weight=EXPAND_NONE) creditsBtn.callback_clicked_add(self.creditsPress) creditsBtn.show() buttonBox.pack_end(creditsBtn) # Close Button okBtn = Button(self.aboutDialog, text=" Close ", size_hint_weight=EXPAND_NONE) okBtn.callback_clicked_add(self.closeabout) okBtn.show() buttonBox.pack_end(okBtn) # Ensure the min height self.aboutDialog.resize(300, 100) def creditsPress(self, obj): # About popup self.popupAbout = Popup(self.aboutDialog, size_hint_weight=EXPAND_BOTH) self.popupAbout.text = ( "Jeff Hoogland <<i>Jef91</i>><br><br>" "Robert Wiley <<i>ylee</i>><br><br>" "Kai Huuhko <<i>kuuko</i>><br>" ) self.popupAbout.callback_block_clicked_add(self.cb_bnt_close) self.popupAbout.show() def cb_bnt_close(self, btn): self.popupAbout.delete() def closeabout(self, obj=False, trash=False): self.aboutDialog.hide() def launch(self, startingFile=False): center = self._parent.mainWindow.center_get() self.aboutDialog.center_set(center[0], center[1]) self.aboutDialog.show()
class Interface(object): def __init__(self): self.mainWindow = StandardWindow("epad", "Untitled - ePad", size=(600, 400)) self.mainWindow.callback_delete_request_add(self.closeChecks) self.mainWindow.elm_event_callback_add(self.eventsCb) icon = Icon(self.mainWindow, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) icon.standard_set('accessories-text-editor') icon.show() self.mainWindow.icon_object_set(icon.object_get()) self.mainBox = Box(self.mainWindow, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.mainBox.show() self.mainTb = ePadToolbar(self, self.mainWindow) self.mainTb.show() self.mainBox.pack_end(self.mainTb) # Initialize Text entry box print("Word wrap Initialized: {0}".format(self.wordwrap)) self.entryInit() # Add label to show current cursor position if SHOW_POS: self.line_label = Label(self.mainWindow, size_hint_weight=EXPAND_HORIZ, size_hint_align=ALIGN_RIGHT) self.curChanged(self.mainEn, self.line_label) self.line_label.show() self.mainBox.pack_end(self.line_label) self.mainEn.callback_cursor_changed_add(self.curChanged, self.line_label) # Build our file selector for saving/loading files self.fileBox = Box(self.mainWindow, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.fileBox.show() self.fileLabel = Label(self.mainWindow, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_BOTH, text="") self.fileLabel.show() self.fileSelector = Fileselector(self.mainWindow, is_save=False, expandable=False, folder_only=False, path=os.getenv("HOME"), size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.fileSelector.callback_done_add(self.fileSelected) self.fileSelector.show() self.fileBox.pack_end(self.fileLabel) self.fileBox.pack_end(self.fileSelector) # Flip object has the file selector on one side # and the GUI on the other self.flip = Flip(self.mainWindow, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.flip.part_content_set("front", self.mainBox) self.flip.part_content_set("back", self.fileBox) self.mainWindow.resize_object_add(self.flip) self.flip.show() self.isSaved = True self.isNewFile = False self.confirmPopup = None def entryInit(self): self.mainEn = Entry(self.mainWindow, scrollable=True, line_wrap=self.wordwrap, autosave=False, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.mainEn.callback_changed_user_add(self.textEdited) self.mainEn.elm_event_callback_add(self.eventsCb) # self.mainEn.markup_filter_append(self.textFilter) self.mainEn.show() self.mainBox.pack_end(self.mainEn) def curChanged(self, entry, label): # get linear index into current text index = entry.cursor_pos_get() # Replace <br /> tag with single char # to simplify (line, col) calculation tmp_text = entry.entry_get().replace("<br/>", "\n") line = tmp_text[:index].count("\n") + 1 col = len(tmp_text[:index].split("\n")[-1]) + 1 # Update label text with line, col label.text = "Ln {0} Col {1} ".format(line, col) def textEdited(self, obj): current_file = self.mainEn.file[0] current_file = \ os.path.basename(current_file) if \ current_file and not self.isNewFile else \ "Untitled" self.mainWindow.title = "*%s - ePad" % (current_file) self.isSaved = False def fileSelected(self, fs, file_selected, onStartup=False): if not onStartup: self.flip.go(ELM_FLIP_INTERACTION_ROTATE) print(file_selected) IsSave = fs.is_save_get() if file_selected: if IsSave: newfile = open(file_selected, 'w') tmp_text = self.mainEn.entry_get() newfile.write(tmp_text) newfile.close() self.mainEn.file_set(file_selected, ELM_TEXT_FORMAT_PLAIN_UTF8) self.mainEn.entry_set(tmp_text) self.mainEn.file_save() self.mainWindow.title_set("%s - ePad" % os.path.basename(file_selected)) self.isSaved = True self.isNewFile = False else: try: self.mainEn.file_set(file_selected, ELM_TEXT_FORMAT_PLAIN_UTF8) except RuntimeError: print("Empty file: {0}".format(file_selected)) self.mainWindow.title_set("%s - ePad" % os.path.basename(file_selected)) def newFile(self, obj=None, ignoreSave=False): if self.isSaved is True or ignoreSave is True: trans = Transit() trans.object_add(self.mainEn) trans.auto_reverse = True trans.effect_wipe_add( ELM_TRANSIT_EFFECT_WIPE_TYPE_HIDE, ELM_TRANSIT_EFFECT_WIPE_DIR_RIGHT) trans.duration = 0.5 trans.go() time.sleep(0.5) self.mainWindow.title_set("Untitled - ePad") self.mainEn.delete() self.entryInit() self.isNewFile = True elif self.confirmPopup is None: self.confirmSave(self.newFile) def openFile(self, obj=None, ignoreSave=False): if self.isSaved is True or ignoreSave is True: self.fileSelector.is_save_set(False) self.fileLabel.text = "<b>Select a text file to open:</b>" self.flip.go(ELM_FLIP_ROTATE_YZ_CENTER_AXIS) elif self.confirmPopup is None: self.confirmSave(self.openFile) def confirmSave(self, ourCallback=None): self.confirmPopup = Popup(self.mainWindow, size_hint_weight=EXPAND_BOTH) self.confirmPopup.part_text_set("title,text", "File Unsaved") current_file = self.mainEn.file[0] current_file = \ os.path.basename(current_file) if current_file else "Untitled" self.confirmPopup.text = "Save changes to '%s'?" % (current_file) # Close without saving button no_btt = Button(self.mainWindow) no_btt.text = "No" no_btt.callback_clicked_add(self.closePopup, self.confirmPopup) if ourCallback is not None: no_btt.callback_clicked_add(ourCallback, True) no_btt.show() # cancel close request cancel_btt = Button(self.mainWindow) cancel_btt.text = "Cancel" cancel_btt.callback_clicked_add(self.closePopup, self.confirmPopup) cancel_btt.show() # Save the file and then close button sav_btt = Button(self.mainWindow) sav_btt.text = "Yes" sav_btt.callback_clicked_add(self.saveFile) sav_btt.callback_clicked_add(self.closePopup, self.confirmPopup) sav_btt.show() # add buttons to popup self.confirmPopup.part_content_set("button1", no_btt) self.confirmPopup.part_content_set("button2", cancel_btt) self.confirmPopup.part_content_set("button3", sav_btt) self.confirmPopup.show() def saveAs(self): self.fileSelector.is_save_set(True) self.fileLabel.text = "<b>Save new file to where:</b>" self.flip.go(ELM_FLIP_ROTATE_XZ_CENTER_AXIS) def saveFile(self, obj=False): if self.mainEn.file_get()[0] is None or self.isNewFile: self.saveAs() else: self.mainEn.file_save() self.mainWindow.title_set("%s - ePad" % os.path.basename(self.mainEn.file[0])) self.isSaved = True def closeChecks(self, obj): print(self.isSaved) if self.isSaved is False and self.confirmPopup is None: self.confirmSave(self.closeApp) else: self.closeApp() def closePopup(self, bt, confirmPopup): self.confirmPopup.delete() self.confirmPopup = None def closeApp(self, obj=False, trash=False): elementary.exit() def eventsCb(self, obj, src, event_type, event): if event.modifier_is_set("Control"): if event.key.lower() == "n": self.newFile() elif event.key.lower() == "s" and event.modifier_is_set("Shift"): self.saveAs() elif event.key.lower() == "s": self.saveFile() elif event.key.lower() == "o": self.openFile() # Legacy hack no longer needed # there was an issue in elementary entry where it would # accept those character controls # def textFilter( self, obj, theText, data ): # # Block ctrl+hot keys used in eventsCb # # # # Ctrl O Ctrl N Ctrl S # ctrl_block = [chr(14), chr(15), chr(19)] # if theText in ctrl_block: # return None # else: # return theText def launch(self, startingFile=False): if startingFile: self.fileSelected(self.fileSelector, startingFile, True) self.mainWindow.show()
class Interface(object): def __init__(self): self.mainWindow = StandardWindow("epad", "Untitled - ePad", size=(600, 400)) self.mainWindow.callback_delete_request_add(self.closeChecks) self.mainWindow.elm_event_callback_add(self.eventsCb) icon = Icon(self.mainWindow, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) icon.standard_set('accessories-text-editor') icon.show() self.mainWindow.icon_object_set(icon.object_get()) self.mainBox = Box(self.mainWindow, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.mainBox.show() self.mainTb = ePadToolbar(self, self.mainWindow) self.mainTb.show() self.mainBox.pack_end(self.mainTb) # Initialize Text entry box print("Word wrap Initialized: {0}".format(self.wordwrap)) self.entryInit() # Add label to show current cursor position if SHOW_POS: self.line_label = Label(self.mainWindow, size_hint_weight=EXPAND_HORIZ, size_hint_align=ALIGN_RIGHT) self.curChanged(self.mainEn, self.line_label) self.line_label.show() self.mainBox.pack_end(self.line_label) self.mainEn.callback_cursor_changed_add(self.curChanged, self.line_label) # Build our file selector for saving/loading files self.fileBox = Box(self.mainWindow, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.fileBox.show() self.fileLabel = Label(self.mainWindow, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_BOTH, text="") self.fileLabel.show() self.fileSelector = Fileselector(self.mainWindow, is_save=False, expandable=False, folder_only=False, path=os.getenv("HOME"), size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.fileSelector.callback_done_add(self.fileSelected) self.fileSelector.show() self.fileBox.pack_end(self.fileLabel) self.fileBox.pack_end(self.fileSelector) # Flip object has the file selector on one side # and the GUI on the other self.flip = Flip(self.mainWindow, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.flip.part_content_set("front", self.mainBox) self.flip.part_content_set("back", self.fileBox) self.mainWindow.resize_object_add(self.flip) self.flip.show() self.isSaved = True self.isNewFile = False self.confirmPopup = None def entryInit(self): self.mainEn = Entry(self.mainWindow, scrollable=True, line_wrap=self.wordwrap, autosave=False, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.mainEn.callback_changed_user_add(self.textEdited) self.mainEn.elm_event_callback_add(self.eventsCb) # self.mainEn.markup_filter_append(self.textFilter) self.mainEn.show() self.mainBox.pack_end(self.mainEn) def curChanged(self, entry, label): # get linear index into current text index = entry.cursor_pos_get() # Replace <br /> tag with single char # to simplify (line, col) calculation tmp_text = entry.entry_get().replace("<br/>", "\n") line = tmp_text[:index].count("\n") + 1 col = len(tmp_text[:index].split("\n")[-1]) + 1 # Update label text with line, col label.text = "Ln {0} Col {1} ".format(line, col) def textEdited(self, obj): current_file = self.mainEn.file[0] current_file = \ os.path.basename(current_file) if \ current_file and not self.isNewFile else \ "Untitled" self.mainWindow.title = "*%s - ePad" % (current_file) self.isSaved = False def fileSelected(self, fs, file_selected, onStartup=False): if not onStartup: self.flip.go(ELM_FLIP_INTERACTION_ROTATE) print(file_selected) IsSave = fs.is_save_get() if file_selected: if IsSave: newfile = open(file_selected, 'w') tmp_text = self.mainEn.entry_get() newfile.write(tmp_text) newfile.close() self.mainEn.file_set(file_selected, ELM_TEXT_FORMAT_PLAIN_UTF8) self.mainEn.entry_set(tmp_text) self.mainEn.file_save() self.mainWindow.title_set("%s - ePad" % os.path.basename(file_selected)) self.isSaved = True self.isNewFile = False else: try: self.mainEn.file_set(file_selected, ELM_TEXT_FORMAT_PLAIN_UTF8) except RuntimeError: print("Empty file: {0}".format(file_selected)) self.mainWindow.title_set("%s - ePad" % os.path.basename(file_selected)) def newFile(self, obj=None, ignoreSave=False): if self.isSaved is True or ignoreSave is True: trans = Transit() trans.object_add(self.mainEn) trans.auto_reverse = True trans.effect_wipe_add(ELM_TRANSIT_EFFECT_WIPE_TYPE_HIDE, ELM_TRANSIT_EFFECT_WIPE_DIR_RIGHT) trans.duration = 0.5 trans.go() time.sleep(0.5) self.mainWindow.title_set("Untitled - ePad") self.mainEn.delete() self.entryInit() self.isNewFile = True elif self.confirmPopup is None: self.confirmSave(self.newFile) def openFile(self, obj=None, ignoreSave=False): if self.isSaved is True or ignoreSave is True: self.fileSelector.is_save_set(False) self.fileLabel.text = "<b>Select a text file to open:</b>" self.flip.go(ELM_FLIP_ROTATE_YZ_CENTER_AXIS) elif self.confirmPopup is None: self.confirmSave(self.openFile) def confirmSave(self, ourCallback=None): self.confirmPopup = Popup(self.mainWindow, size_hint_weight=EXPAND_BOTH) self.confirmPopup.part_text_set("title,text", "File Unsaved") current_file = self.mainEn.file[0] current_file = \ os.path.basename(current_file) if current_file else "Untitled" self.confirmPopup.text = "Save changes to '%s'?" % (current_file) # Close without saving button no_btt = Button(self.mainWindow) no_btt.text = "No" no_btt.callback_clicked_add(self.closePopup, self.confirmPopup) if ourCallback is not None: no_btt.callback_clicked_add(ourCallback, True) no_btt.show() # cancel close request cancel_btt = Button(self.mainWindow) cancel_btt.text = "Cancel" cancel_btt.callback_clicked_add(self.closePopup, self.confirmPopup) cancel_btt.show() # Save the file and then close button sav_btt = Button(self.mainWindow) sav_btt.text = "Yes" sav_btt.callback_clicked_add(self.saveFile) sav_btt.callback_clicked_add(self.closePopup, self.confirmPopup) sav_btt.show() # add buttons to popup self.confirmPopup.part_content_set("button1", no_btt) self.confirmPopup.part_content_set("button2", cancel_btt) self.confirmPopup.part_content_set("button3", sav_btt) self.confirmPopup.show() def saveAs(self): self.fileSelector.is_save_set(True) self.fileLabel.text = "<b>Save new file to where:</b>" self.flip.go(ELM_FLIP_ROTATE_XZ_CENTER_AXIS) def saveFile(self, obj=False): if self.mainEn.file_get()[0] is None or self.isNewFile: self.saveAs() else: self.mainEn.file_save() self.mainWindow.title_set("%s - ePad" % os.path.basename(self.mainEn.file[0])) self.isSaved = True def closeChecks(self, obj): print(self.isSaved) if self.isSaved is False and self.confirmPopup is None: self.confirmSave(self.closeApp) else: self.closeApp() def closePopup(self, bt, confirmPopup): self.confirmPopup.delete() self.confirmPopup = None def closeApp(self, obj=False, trash=False): elementary.exit() def eventsCb(self, obj, src, event_type, event): if event.modifier_is_set("Control"): if event.key.lower() == "n": self.newFile() elif event.key.lower() == "s" and event.modifier_is_set("Shift"): self.saveAs() elif event.key.lower() == "s": self.saveFile() elif event.key.lower() == "o": self.openFile() # Legacy hack no longer needed # there was an issue in elementary entry where it would # accept those character controls # def textFilter( self, obj, theText, data ): # # Block ctrl+hot keys used in eventsCb # # # # Ctrl O Ctrl N Ctrl S # ctrl_block = [chr(14), chr(15), chr(19)] # if theText in ctrl_block: # return None # else: # return theText def launch(self, startingFile=False): if startingFile: self.fileSelected(self.fileSelector, startingFile, True) self.mainWindow.show()
class FileSelector(Box): def __init__(self, parent_widget, defaultPath="", defaultPopulate=True, *args, **kwargs): Box.__init__(self, parent_widget, *args, **kwargs) self.cancelCallback = None self.actionCallback = None self.directoryChangeCallback = None self.threadedFunction = ThreadedFunction() self._timer = ecore.Timer(0.02, self.populateFile) #Watch key presses for ctrl+l to select entry parent_widget.elm_event_callback_add(self.eventsCb) self.selectedFolder = None self.showHidden = False self.currentDirectory = None self.focusedEntry = None self.folderOnly = False self.sortReverse = False self.addingHidden = False self.pendingFiles = deque() self.currentSubFolders = [] self.currentFiles = [] #Mode should be "save" or "load" self.mode = "save" self.home = os.path.expanduser("~") self.root = "/" #Label+Entry for File Name self.filenameBox = Box(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ) self.filenameBox.horizontal = True self.filenameBox.show() fileLabel = Label(self, size_hint_weight=(0.15, EVAS_HINT_EXPAND), size_hint_align=FILL_HORIZ) fileLabel.text = "Filename:" fileLabel.show() self.fileEntry = Entry(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_HORIZ) self.fileEntry.single_line_set(True) self.fileEntry.scrollable_set(True) self.fileEntry.callback_changed_user_add(self.fileEntryChanged) self.fileEntry.show() self.filenameBox.pack_end(fileLabel) self.filenameBox.pack_end(self.fileEntry) sep = Separator(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ) sep.horizontal_set(True) sep.show() #Label+Entry for File Path self.filepathBox = Box(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ) self.filepathBox.horizontal = True self.filepathBox.show() fileLabel = Label(self, size_hint_weight=(0.15, EVAS_HINT_EXPAND), size_hint_align=FILL_HORIZ) fileLabel.text = "Current Folder:" fileLabel.show() self.filepathEntry = Entry(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_HORIZ) self.filepathEntry.single_line_set(True) self.filepathEntry.scrollable_set(True) self.filepathEntry.callback_changed_user_add(self.fileEntryChanged) self.filepathEntry.callback_unfocused_add(self.filepathEditDone) self.filepathEntry.callback_activated_add(self.filepathEditDone) #Wish this worked. Doesn't seem to do anything #self.filepathEntry.input_hint_set(ELM_INPUT_HINT_AUTO_COMPLETE) if defaultPath and os.path.isdir(defaultPath): startPath = defaultPath else: startPath = self.home self.filepathEntry.show() self.filepathBox.pack_end(fileLabel) self.filepathBox.pack_end(self.filepathEntry) self.autocompleteHover = Hoversel(self, hover_parent=self) self.autocompleteHover.callback_selected_add(self.autocompleteSelected) #self.autocompleteHover.show() self.fileSelectorBox = Panes(self, content_left_size=0.3, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.fileSelectorBox.show() """Bookmarks Box contains: - Button - Up Arrow - List - Home/Root/GTK bookmarks - Box -- Button - Add Bookmark -- Button - Remove Bookmark""" self.bookmarkBox = Box(self, size_hint_weight=(0.3, EVAS_HINT_EXPAND), size_hint_align=FILL_BOTH) self.bookmarkBox.show() upIcon = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) upIcon.standard_set("go-up") upIcon.show() self.upButton = Button(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ, content=upIcon) self.upButton.text = "Up" self.upButton.callback_pressed_add(self.upButtonPressed) self.upButton.show() self.bookmarksList = List(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.bookmarksList.callback_activated_add(self.bookmarkDoubleClicked) self.bookmarksList.show() self.bookmarkModBox = Box(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ) self.bookmarkModBox.horizontal = True self.bookmarkModBox.show() con = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) con.standard_set("add") con.show() self.addButton = Button(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ, content=con) self.addButton.callback_pressed_add(self.addButtonPressed) self.addButton.disabled = True self.addButton.show() con = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) con.standard_set("remove") con.show() self.removeButton = Button(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ, content=con) self.removeButton.callback_pressed_add(self.removeButtonPressed) self.removeButton.disabled = True self.removeButton.show() self.bookmarkModBox.pack_end(self.addButton) self.bookmarkModBox.pack_end(self.removeButton) self.bookmarkBox.pack_end(self.upButton) self.bookmarkBox.pack_end(self.bookmarksList) self.bookmarkBox.pack_end(self.bookmarkModBox) #Directory List self.fileListBox = Box(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.fileListBox.show() self.fileSortButton = Button(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ) self.fileSortButton.text = u"⬆ Name" self.fileSortButton.callback_pressed_add(self.sortData) self.fileSortButton.show() self.fileList = Genlist(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH, homogeneous=True, mode=ELM_LIST_COMPRESS) self.fileList.callback_activated_add(self.fileDoubleClicked) self.fileList.show() self.previewImage = previewImage = Image(self) #previewImage.size_hint_weight = EXPAND_BOTH previewImage.size_hint_align = FILL_BOTH previewImage.show() self.fileListBox.pack_end(self.fileSortButton) self.fileListBox.pack_end(self.fileList) self.fileListBox.pack_end(self.previewImage) self.fileSelectorBox.part_content_set("left", self.bookmarkBox) self.fileSelectorBox.part_content_set("right", self.fileListBox) #Cancel and Save/Open button self.buttonBox = Box(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=(1.0, 0.5)) self.buttonBox.horizontal = True self.buttonBox.show() self.actionIcon = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.actionIcon.standard_set("document-save") self.actionIcon.show() self.actionButton = Button(self, size_hint_weight=(0.0, 0.0), size_hint_align=(1.0, 0.5), content=self.actionIcon) self.actionButton.text = "Save " self.actionButton.callback_pressed_add(self.actionButtonPressed) self.actionButton.show() cancelIcon = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) cancelIcon.standard_set("exit") cancelIcon.show() self.cancelButton = Button(self, size_hint_weight=(0.0, 0.0), size_hint_align=(1.0, 0.5), content=cancelIcon) self.cancelButton.text = "Cancel " self.cancelButton.callback_pressed_add(self.cancelButtonPressed) self.cancelButton.show() con = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) con.standard_set("gtk-find") con.show() self.toggleHiddenButton = Button(self, size_hint_weight=(0.0, 0.0), size_hint_align=(1.0, 0.5), content=con) self.toggleHiddenButton.text = "Toggle Hidden " self.toggleHiddenButton.callback_pressed_add(self.toggleHiddenButtonPressed) self.toggleHiddenButton.show() con = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) con.standard_set("folder-new") con.show() self.createFolderButton = Button(self, size_hint_weight=(0.0, 0.0), size_hint_align=(1.0, 0.5), content=con) self.createFolderButton.text = "Create Folder " self.createFolderButton.callback_pressed_add(self.createFolderButtonPressed) self.createFolderButton.show() self.buttonBox.pack_end(self.createFolderButton) self.buttonBox.pack_end(self.toggleHiddenButton) self.buttonBox.pack_end(self.cancelButton) self.buttonBox.pack_end(self.actionButton) self.pack_end(self.filenameBox) self.pack_end(sep) self.pack_end(self.filepathBox) self.pack_end(self.autocompleteHover) self.pack_end(self.fileSelectorBox) self.pack_end(self.buttonBox) self.populateBookmarks() self.createPopup = Popup(self) self.createPopup.part_text_set("title,text", "Create Folder:") self.createEn = en = Entry(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ) en.single_line_set(True) en.scrollable_set(True) en.show() self.createPopup.content = en bt = Button(self, text="Create") bt.callback_clicked_add(self.createFolder) self.createPopup.part_content_set("button1", bt) bt2 = Button(self, text="Cancel") bt2.callback_clicked_add(self.closePopup) self.createPopup.part_content_set("button2", bt2) if defaultPopulate: self.populateFiles(startPath) def folderOnlySet(self, ourValue): self.folderOnly = ourValue if not self.folderOnly: self.filenameBox.show() else: self.filenameBox.hide() def createFolder(self, obj): newDir = "%s%s"%(self.currentDirectory, self.createEn.text) os.makedirs(newDir) self.closePopup() self.populateFiles(self.currentDirectory) def createFolderButtonPressed(self, obj): self.createEn.text = "" self.createPopup.show() self.createEn.select_all() def closePopup(self, btn=None): self.createPopup.hide() def shutdown(self, obj=None): self._timer.delete() self.threadedFunction.shutdown() def sortData(self, btn): self.sortReverse = not self.sortReverse if self.sortReverse: self.fileSortButton.text = u"⬇ Name" else: self.fileSortButton.text = u"⬆ Name" self.populateFiles(self.currentDirectory) def populateBookmarks(self): con = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) con.standard_set("folder_home") con.show() it = self.bookmarksList.item_append("Home", icon=con) it.data["path"] = self.home con = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) con.standard_set("drive-harddisk") con.show() it = self.bookmarksList.item_append("Root", icon=con) it.data["path"] = self.root it = self.bookmarksList.item_append("") it.separator_set(True) for bk in self.getGTKBookmarks(): con = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) con.standard_set("gtk-directory") con.show() it = self.bookmarksList.item_append(bk.split("/")[-1], icon=con) it.data["path"] = bk[7:] def populateFile(self): pen_file = len(self.pendingFiles) if pen_file: for _ in range(int(math.sqrt(pen_file))): ourPath, d, isDir = self.pendingFiles.popleft() self.packFileFolder(ourPath, d, isDir) #else: # self._timer.freeze() return True def populateFiles(self, ourPath): self.autocompleteHover.hover_end() self.pendingFiles.clear() if ourPath[:-1] != "/": ourPath = ourPath + "/" if ourPath != self.filepathEntry.text or not self.showHidden: self.addingHidden = False if self.directoryChangeCallback: self.directoryChangeCallback(ourPath) del self.currentSubFolders[:] del self.currentFiles[:] self.fileList.clear() else: self.addingHidden = True self.filepathEntry.text = ourPath.replace("//", "/") self.currentDirectory = ourPath.replace("//", "/") self.threadedFunction.run(self.getFolderContents) #self._timer.thaw() def getFolderContents(self): ourPath = self.currentDirectory try: data = os.listdir(unicode(ourPath)) except: data = os.listdir(str(ourPath)) sortedData = [] for d in data: isDir = os.path.isdir("%s%s"%(ourPath, d)) if isDir: self.currentSubFolders.append(d) if self.sortReverse: sortedData.append([1, d]) else: sortedData.append([0, d]) else: self.currentFiles.append(d) if self.sortReverse: sortedData.append([0, d]) else: sortedData.append([1, d]) sortedData.sort(reverse=self.sortReverse) for ourFile in sortedData: d = ourFile[1] isDir = ourFile[0] if self.sortReverse else not ourFile[0] if self.addingHidden and d[0] == ".": self.pendingFiles.append([ourPath, d, isDir]) elif (d[0] != "." or self.showHidden) and not self.addingHidden: self.pendingFiles.append([ourPath, d, isDir]) def packFileFolder(self, ourPath, d, isDir): if isDir: li = GenlistItem(item_data={"type": "dir", "path": ourPath, "d": d}, item_class=dirglic, func=self.listItemSelected) else: li = GenlistItem(item_data={"type": "file", "path": ourPath, "d": d}, item_class=fileglic, func=self.listItemSelected) li.append_to(self.fileList) #self.fileList.go() #print("Adding: %s %s %s"%(ourPath, d, isDir)) def fileDoubleClicked(self, obj, item=None, eventData=None): if item.data["type"] == "dir": self.addButton.disabled = True self.removeButton.disabled = True self.populateFiles(item.data["path"]+item.text) else: self.actionButtonPressed(self.actionButton) def getGTKBookmarks(self): try: with open(os.path.expanduser('~/.config/gtk-3.0/bookmarks'),'r') as f: ourBks = [] for x in f: x = x.split(" ")[0] x = x.replace("%20", " ") x = x.strip() ourBks.append(x) return ourBks except IOError: return [] def bookmarkDoubleClicked(self, obj, item=None, eventData=None): item.selected_set(False) self.addButton.disabled = True self.removeButton.disabled = True self.populateFiles(item.data["path"]) def listItemSelected(self, item, gl, data): if item.data["type"] == "dir": self.directorySelected(item) else: self.fileSelected(item.text) item.selected_set(False) def fileSelected(self, ourFile): self.fileEntry.text = ourFile self.addButton.disabled = True self.removeButton.disabled = True self.selectedFolder = None #Update image preview if an image is selected if ourFile[-3:] in ["jpg", "png", "gif"]: self.previewImage.file_set("%s/%s"%(self.filepathEntry.text, ourFile)) self.previewImage.size_hint_weight = (1.0, 0.4) else: self.previewImage.size_hint_weight = (0, 0) def directorySelected(self, btn): ourPath = btn.data["path"] if btn == self.selectedFolder: self.populateFiles(ourPath) self.addButton.disabled = True else: self.selectedFolder = btn currentMarks = self.getGTKBookmarks() toAppend = "file://%s%s"%(self.filepathEntry.text, self.selectedFolder.text) if toAppend not in currentMarks: self.addButton.disabled = False self.removeButton.disabled = True else: self.addButton.disabled = True self.removeButton.disabled = False def upButtonPressed(self, btn): ourSplit = self.filepathEntry.text.split("/") del ourSplit[-1] del ourSplit[-1] self.populateFiles("/".join(ourSplit)) def addButtonPressed(self, btn): toAppend = "file://%s%s"%(self.filepathEntry.text, self.selectedFolder.text.replace(" ", "%20")) con = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) con.standard_set("gtk-directory") con.show() it = self.bookmarksList.item_append(self.selectedFolder.text, icon=con) it.data["path"] = "%s%s"%(self.filepathEntry.text, self.selectedFolder.text) self.bookmarksList.go() self.addButton.disabled = True self.removeButton.disabled = False with open(os.path.expanduser('~/.config/gtk-3.0/bookmarks'),'a') as f: f.write( toAppend + " " + self.selectedFolder.text + "\n" ) def removeButtonPressed(self, btn): toRemove = "file://%s%s"%(self.filepathEntry.text, self.selectedFolder.text) bks = self.getGTKBookmarks() bks.remove(toRemove) with open(os.path.expanduser('~/.config/gtk-3.0/bookmarks'),'w') as f: for b in bks: bName = b.split("/")[-1] b = b.replace(" ", "%20") f.write( b + " " + bName + "\n" ) self.bookmarksList.clear() self.populateBookmarks() self.addButton.disabled = False self.removeButton.disabled = True def setMode(self, ourMode): self.mode = ourMode.lower() self.actionButton.text = "%s "%ourMode self.actionIcon.standard_set("document-%s"%ourMode.lower()) if self.mode != "save": self.createFolderButton.hide() else: self.createFolderButton.show() def eventsCb(self, obj, src, event_type, event): if event.modifier_is_set("Control") and event_type == EVAS_CALLBACK_KEY_DOWN: if event.key.lower() == "l": self.filepathEntry.focus_set(True) self.filepathEntry.cursor_end_set() def toggleHiddenButtonPressed(self, btn): self.showHidden = not self.showHidden self.populateFiles(self.filepathEntry.text) def toggleHidden(self): self.showHidden = not self.showHidden self.populateFiles(self.filepathEntry.text) def callback_cancel_add(self, cb): self.cancelCallback = cb def callback_activated_add(self, cb): self.actionCallback = cb def callback_directory_open_add(self, cb): self.directoryChangeCallback = cb def cancelButtonPressed(self, btn): if self.cancelCallback: self.cancelCallback(self) def actionButtonPressed(self, btn): if self.actionCallback: if not self.folderOnly and self.fileEntry.text: self.actionCallback(self, "%s%s"%(self.filepathEntry.text, self.fileEntry.text)) elif self.folderOnly: self.actionCallback(self, "%s"%(self.filepathEntry.text)) def fileEntryChanged(self, en): typed = en.text.split("/")[-1] newList = [] self.focusedEntry = en if en == self.filepathEntry: for x in self.currentSubFolders: if typed in x: if len(newList) < 10: newList.append(x) else: break else: for x in self.currentFiles: if typed in x: if len(newList) < 10: newList.append(x) else: break if self.autocompleteHover.expanded_get(): self.autocompleteHover.hover_end() self.autocompleteHover.clear() for x in newList: self.autocompleteHover.item_add(x) self.autocompleteHover.hover_begin() def autocompleteSelected(self, hov, item): hov.hover_end() if self.focusedEntry == self.filepathEntry: self.populateFiles("%s%s"%(self.currentDirectory, item.text)) self.filepathEntry.cursor_end_set() else: self.fileEntry.text = item.text self.fileEntry.cursor_end_set() def filepathEditDone(self, en): if os.path.isdir(en.text) and en.text != self.currentDirectory: self.populateFiles(en.text) self.filepathEntry.cursor_end_set() else: #en.text = self.currentDirectory pass def selected_get(self): return "%s%s"%(self.filepathEntry.text, self.fileEntry.text)
def cb_popup_center_text(li, item, win): popup = Popup(win, size_hint_weight=EXPAND_BOTH, timeout=3.0) popup.text = "This Popup has content area and timeout value is 3 seconds" popup.show()
class Interface(object): def __init__(self): self.mainWindow = StandardWindow("epad", "Untitled - ePad", size=(600, 400)) self.mainWindow.callback_delete_request_add(self.closeChecks) self.mainWindow.elm_event_callback_add(self.eventsCb) icon = Icon(self.mainWindow) icon.size_hint_weight_set(EVAS_HINT_EXPAND, EVAS_HINT_EXPAND) icon.size_hint_align_set(EVAS_HINT_FILL, EVAS_HINT_FILL) icon.standard_set( 'accessories-text-editor' ) # assumes image icon is in local dir, may need to change later icon.show() self.mainWindow.icon_object_set(icon.object_get()) self.mainBox = Box(self.mainWindow, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.mainBox.show() self.mainTb = Toolbar(self.mainWindow, homogeneous=False, size_hint_weight=(0.0, 0.0), size_hint_align=(EVAS_HINT_FILL, 0.0)) self.mainTb.menu_parent = self.mainWindow self.mainTb.item_append("document-new", "New", self.newPress) self.mainTb.item_append("document-open", "Open", self.openPress) self.mainTb.item_append("document-save", "Save", self.savePress) self.mainTb.item_append("document-save-as", "Save As", self.saveAsPress) # -- Edit Dropdown Menu -- tb_it = self.mainTb.item_append("edit", "Edit") tb_it.menu = True menu = tb_it.menu menu.item_add(None, "Copy", "edit-copy", self.copyPress) menu.item_add(None, "Paste", "edit-paste", self.pastePress) menu.item_add(None, "Cut", "edit-cut", self.cutPress) menu.item_separator_add() menu.item_add(None, "Select All", "edit-select-all", self.selectAllPress) # ----------------------- # self.mainTb.item_append("settings", "Options", self.optionsPress) self.mainTb.item_append("dialog-information", "About", self.aboutPress) self.mainEn = Entry(self.mainWindow, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.mainEn.callback_changed_user_add(self.textEdited) self.mainEn.scrollable_set( True) # creates scrollbars rather than enlarge window self.mainEn.line_wrap_set( False) # does not allow line wrap (can be changed by user) self.mainEn.autosave_set(False) # set to false to reduce disk I/O self.mainEn.elm_event_callback_add(self.eventsCb) self.mainEn.markup_filter_append(self.textFilter) self.mainEn.show() self.mainTb.show() self.mainBox.pack_end(self.mainTb) self.mainBox.pack_end(self.mainEn) #Build our file selector for saving/loading files self.fileBox = Box(self.mainWindow, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.fileBox.show() self.fileLabel = Label(self.mainWindow, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_BOTH) self.fileLabel.text = "" self.fileLabel.show() self.fileSelector = Fileselector(self.mainWindow, is_save=False, expandable=False, folder_only=False, path=os.getenv("HOME"), size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.fileSelector.callback_done_add(self.fileSelected) #self.fileSelector.callback_selected_add(fs_cb_selected, win) #self.fileSelector.callback_directory_open_add(fs_cb_directory_open, win) self.fileSelector.show() self.fileBox.pack_end(self.fileLabel) self.fileBox.pack_end(self.fileSelector) # the flip object has the file selector on one side and the GUI on the other self.flip = Flip(self.mainWindow, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.flip.part_content_set("front", self.mainBox) self.flip.part_content_set("back", self.fileBox) self.mainWindow.resize_object_add(self.flip) self.flip.show() self.isSaved = True self.isNewFile = False self.confirmPopup = None def newPress(self, obj, it): self.newFile() it.selected_set(False) def openPress(self, obj, it): self.openFile() it.selected_set(False) def savePress(self, obj, it): self.saveFile() it.selected_set(False) def saveAsPress(self, obj, it): self.saveAs() it.selected_set(False) def optionsPress(self, obj, it): it.selected_set(False) def copyPress(self, obj, it): self.mainEn.selection_copy() it.selected_set(False) def pastePress(self, obj, it): self.mainEn.selection_paste() it.selected_set(False) def cutPress(self, obj, it): self.mainEn.selection_cut() it.selected_set(False) def selectAllPress(self, obj, it): self.mainEn.select_all() it.selected_set(False) def textEdited(self, obj): ourFile = self.mainEn.file_get()[0] if ourFile and not self.isNewFile: self.mainWindow.title_set( "*%s - ePad" % self.mainEn.file_get()[0].split("/")[ len(self.mainEn.file_get()[0].split("/")) - 1]) else: self.mainWindow.title_set("*Untitlted - ePad") self.isSaved = False def fileSelected(self, fs, file_selected, onStartup=False): if not onStartup: self.flip.go(ELM_FLIP_INTERACTION_ROTATE) print(file_selected) IsSave = fs.is_save_get() if file_selected: if IsSave: newfile = open(file_selected, 'w') # creates new file tmp_text = self.mainEn.entry_get() newfile.write(tmp_text) newfile.close() self.mainEn.file_set(file_selected, ELM_TEXT_FORMAT_PLAIN_UTF8) self.mainEn.entry_set(tmp_text) self.mainEn.file_save() self.mainWindow.title_set( "%s - ePad" % file_selected.split("/")[len(file_selected.split("/")) - 1]) self.isSaved = True self.isNewFile = False else: try: self.mainEn.file_set(file_selected, ELM_TEXT_FORMAT_PLAIN_UTF8) except RuntimeError: print("Empty file: {0}".format(file_selected)) self.mainWindow.title_set( "%s - ePad" % file_selected.split("/")[len(file_selected.split("/")) - 1]) def aboutPress(self, obj, it): #About popup self.popupAbout = Popup(self.mainWindow, size_hint_weight=EXPAND_BOTH) self.popupAbout.text = "ePad - A simple text editor written in python and elementary<br><br> " \ "By: Jeff Hoogland" bt = Button(self.mainWindow, text="Done") bt.callback_clicked_add(self.aboutClose) self.popupAbout.part_content_set("button1", bt) self.popupAbout.show() it.selected_set(False) def aboutClose(self, bt): self.popupAbout.delete() def newFile(self, obj=None, ignoreSave=False): if self.isSaved == True or ignoreSave == True: trans = Transit() trans.object_add(self.mainEn) trans.auto_reverse = True trans.effect_wipe_add(ELM_TRANSIT_EFFECT_WIPE_TYPE_HIDE, ELM_TRANSIT_EFFECT_WIPE_DIR_RIGHT) trans.duration = 0.5 trans.go() time.sleep(0.5) self.mainWindow.title_set("Untitlted - ePad") self.mainEn.delete() self.mainEn = Entry(self.mainWindow, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.mainEn.callback_changed_user_add(self.textEdited) self.mainEn.scrollable_set( True) # creates scrollbars rather than enlarge window self.mainEn.line_wrap_set( False) # does not allow line wrap (can be changed by user) self.mainEn.autosave_set(False) # set to false to reduce disk I/O self.mainEn.elm_event_callback_add(self.eventsCb) self.mainEn.markup_filter_append(self.textFilter) self.mainEn.show() self.mainBox.pack_end(self.mainEn) self.isNewFile = True elif self.confirmPopup == None: self.confirmSave(self.newFile) def openFile(self, obj=None, ignoreSave=False): if self.isSaved == True or ignoreSave == True: self.fileSelector.is_save_set(False) self.fileLabel.text = "<b>Select a text file to open:</b>" self.flip.go(ELM_FLIP_ROTATE_YZ_CENTER_AXIS) elif self.confirmPopup == None: self.confirmSave(self.openFile) def confirmSave(self, ourCallback=None): self.confirmPopup = Popup(self.mainWindow, size_hint_weight=EXPAND_BOTH) self.confirmPopup.part_text_set("title,text", "File Unsaved") if self.mainEn.file_get()[0]: self.confirmPopup.text = "Save changes to '%s'?" % self.mainEn.file_get( )[0].split("/")[len(self.mainEn.file_get()[0].split("/")) - 1] else: self.confirmPopup.text = "Save changes to 'Untitlted'?" # Close without saving button no_btt = Button(self.mainWindow) no_btt.text = "No" no_btt.callback_clicked_add(self.closePopup, self.confirmPopup) if ourCallback is not None: no_btt.callback_clicked_add(ourCallback, True) no_btt.show() # cancel close request cancel_btt = Button(self.mainWindow) cancel_btt.text = "Cancel" cancel_btt.callback_clicked_add(self.closePopup, self.confirmPopup) cancel_btt.show() # Save the file and then close button sav_btt = Button(self.mainWindow) sav_btt.text = "Yes" sav_btt.callback_clicked_add(self.saveFile) sav_btt.callback_clicked_add(self.closePopup, self.confirmPopup) sav_btt.show() # add buttons to popup self.confirmPopup.part_content_set("button1", no_btt) self.confirmPopup.part_content_set("button2", cancel_btt) self.confirmPopup.part_content_set("button3", sav_btt) self.confirmPopup.show() def saveAs(self): self.fileSelector.is_save_set(True) self.fileLabel.text = "<b>Save new file to where:</b>" self.flip.go(ELM_FLIP_ROTATE_XZ_CENTER_AXIS) def saveFile(self, obj=False): if self.mainEn.file_get()[0] == None or self.isNewFile: self.saveAs() else: self.mainEn.file_save() self.mainWindow.title_set( "%s - ePad" % self.mainEn.file_get()[0].split("/")[ len(self.mainEn.file_get()[0].split("/")) - 1]) self.isSaved = True def closeChecks(self, obj): print(self.isSaved) if self.isSaved == False and self.confirmPopup == None: self.confirmSave(self.closeApp) else: self.closeApp() def closePopup(self, bt, confirmPopup): self.confirmPopup.delete() self.confirmPopup = None def closeApp(self, obj=False, trash=False): elementary.exit() def eventsCb(self, obj, src, event_type, event): #print event_type #print event.key #print "Control Key Status: %s" %event.modifier_is_set("Control") #print "Shift Key Status: %s" %event.modifier_is_set("Shift") #print event.modifier_is_set("Alt") if event.modifier_is_set("Control"): if event.key.lower() == "n": self.newFile() elif event.key.lower() == "s" and event.modifier_is_set("Shift"): self.saveAs() elif event.key.lower() == "s": self.saveFile() elif event.key.lower() == "o": self.openFile() def textFilter(self, obj, theText, data): #print theText #Block ctrl+hot keys if theText == "" or theText == "" or theText == "": return None else: return theText def launch(self, startingFile=False): if startingFile: self.fileSelected(self.fileSelector, startingFile, True) self.mainWindow.show()
class FileSelector(Box): def __init__(self, parent_widget, defaultPath="", defaultPopulate=True, *args, **kwargs): Box.__init__(self, parent_widget, *args, **kwargs) self.cancelCallback = None self.actionCallback = None self.directoryChangeCallback = None self.threadedFunction = ThreadedFunction() self._timer = ecore.Timer(0.02, self.populateFile) #Watch key presses for ctrl+l to select entry parent_widget.elm_event_callback_add(self.eventsCb) self.selectedFolder = None self.showHidden = False self.currentDirectory = None self.focusedEntry = None self.folderOnly = False self.sortReverse = False self.addingHidden = False self.pendingFiles = deque() self.currentSubFolders = [] self.currentFiles = [] #Mode should be "save" or "load" self.mode = "save" self.home = os.path.expanduser("~") self.root = "/" #Label+Entry for File Name self.filenameBox = Box(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ) self.filenameBox.horizontal = True self.filenameBox.show() fileLabel = Label(self, size_hint_weight=(0.15, EVAS_HINT_EXPAND), size_hint_align=FILL_HORIZ) fileLabel.text = "Filename:" fileLabel.show() self.fileEntry = Entry(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_HORIZ) self.fileEntry.single_line_set(True) self.fileEntry.scrollable_set(True) self.fileEntry.callback_changed_user_add(self.fileEntryChanged) self.fileEntry.show() self.filenameBox.pack_end(fileLabel) self.filenameBox.pack_end(self.fileEntry) sep = Separator(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ) sep.horizontal_set(True) sep.show() #Label+Entry for File Path self.filepathBox = Box(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ) self.filepathBox.horizontal = True self.filepathBox.show() fileLabel = Label(self, size_hint_weight=(0.15, EVAS_HINT_EXPAND), size_hint_align=FILL_HORIZ) fileLabel.text = "Current Folder:" fileLabel.show() self.filepathEntry = Entry(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_HORIZ) self.filepathEntry.single_line_set(True) self.filepathEntry.scrollable_set(True) self.filepathEntry.callback_changed_user_add(self.fileEntryChanged) self.filepathEntry.callback_unfocused_add(self.filepathEditDone) self.filepathEntry.callback_activated_add(self.filepathEditDone) #Wish this worked. Doesn't seem to do anything #self.filepathEntry.input_hint_set(ELM_INPUT_HINT_AUTO_COMPLETE) if defaultPath and os.path.isdir(defaultPath): startPath = defaultPath else: startPath = self.home self.filepathEntry.show() self.filepathBox.pack_end(fileLabel) self.filepathBox.pack_end(self.filepathEntry) self.autocompleteHover = Hoversel(self, hover_parent=self) self.autocompleteHover.callback_selected_add(self.autocompleteSelected) #self.autocompleteHover.show() self.fileSelectorBox = Panes(self, content_left_size=0.3, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.fileSelectorBox.show() """Bookmarks Box contains: - Button - Up Arrow - List - Home/Root/GTK bookmarks - Box -- Button - Add Bookmark -- Button - Remove Bookmark""" self.bookmarkBox = Box(self, size_hint_weight=(0.3, EVAS_HINT_EXPAND), size_hint_align=FILL_BOTH) self.bookmarkBox.show() upIcon = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) upIcon.standard_set("go-up") upIcon.show() self.upButton = Button(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ, content=upIcon) self.upButton.text = "Up" self.upButton.callback_pressed_add(self.upButtonPressed) self.upButton.show() self.bookmarksList = List(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.bookmarksList.callback_activated_add(self.bookmarkDoubleClicked) self.bookmarksList.show() self.bookmarkModBox = Box(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ) self.bookmarkModBox.horizontal = True self.bookmarkModBox.show() con = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) con.standard_set("add") con.show() self.addButton = Button(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ, content=con) self.addButton.callback_pressed_add(self.addButtonPressed) self.addButton.disabled = True self.addButton.show() con = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) con.standard_set("remove") con.show() self.removeButton = Button(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ, content=con) self.removeButton.callback_pressed_add(self.removeButtonPressed) self.removeButton.disabled = True self.removeButton.show() self.bookmarkModBox.pack_end(self.addButton) self.bookmarkModBox.pack_end(self.removeButton) self.bookmarkBox.pack_end(self.upButton) self.bookmarkBox.pack_end(self.bookmarksList) self.bookmarkBox.pack_end(self.bookmarkModBox) #Directory List self.fileListBox = Box(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.fileListBox.show() self.fileSortButton = Button(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ) self.fileSortButton.text = u"⬆ Name" self.fileSortButton.callback_pressed_add(self.sortData) self.fileSortButton.show() self.fileList = Genlist(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH, homogeneous=True, mode=ELM_LIST_COMPRESS) self.fileList.callback_activated_add(self.fileDoubleClicked) self.fileList.show() self.previewImage = previewImage = Image(self) #previewImage.size_hint_weight = EXPAND_BOTH previewImage.size_hint_align = FILL_BOTH previewImage.show() self.fileListBox.pack_end(self.fileSortButton) self.fileListBox.pack_end(self.fileList) self.fileListBox.pack_end(self.previewImage) self.fileSelectorBox.part_content_set("left", self.bookmarkBox) self.fileSelectorBox.part_content_set("right", self.fileListBox) #Cancel and Save/Open button self.buttonBox = Box(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=(1.0, 0.5)) self.buttonBox.horizontal = True self.buttonBox.show() self.actionIcon = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.actionIcon.standard_set("document-save") self.actionIcon.show() self.actionButton = Button(self, size_hint_weight=(0.0, 0.0), size_hint_align=(1.0, 0.5), content=self.actionIcon) self.actionButton.text = "Save " self.actionButton.callback_pressed_add(self.actionButtonPressed) self.actionButton.show() cancelIcon = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) cancelIcon.standard_set("dialog-cancel") cancelIcon.show() self.cancelButton = Button(self, size_hint_weight=(0.0, 0.0), size_hint_align=(1.0, 0.5), content=cancelIcon) self.cancelButton.text = "Cancel " self.cancelButton.callback_pressed_add(self.cancelButtonPressed) self.cancelButton.show() con = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) con.standard_set("gtk-find") con.show() self.toggleHiddenButton = Button(self, size_hint_weight=(0.0, 0.0), size_hint_align=(1.0, 0.5), content=con) self.toggleHiddenButton.text = "Toggle Hidden " self.toggleHiddenButton.callback_pressed_add( self.toggleHiddenButtonPressed) self.toggleHiddenButton.show() con = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) con.standard_set("folder-new") con.show() self.createFolderButton = Button(self, size_hint_weight=(0.0, 0.0), size_hint_align=(1.0, 0.5), content=con) self.createFolderButton.text = "Create Folder " self.createFolderButton.callback_pressed_add( self.createFolderButtonPressed) self.createFolderButton.show() self.buttonBox.pack_end(self.createFolderButton) self.buttonBox.pack_end(self.toggleHiddenButton) self.buttonBox.pack_end(self.cancelButton) self.buttonBox.pack_end(self.actionButton) self.pack_end(self.filenameBox) self.pack_end(sep) self.pack_end(self.filepathBox) self.pack_end(self.autocompleteHover) self.pack_end(self.fileSelectorBox) self.pack_end(self.buttonBox) self.populateBookmarks() self.createPopup = Popup(self) self.createPopup.part_text_set("title,text", "Create Folder:") self.createEn = en = Entry(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ) en.single_line_set(True) en.scrollable_set(True) en.show() self.createPopup.content = en bt = Button(self, text="Create") bt.callback_clicked_add(self.createFolder) self.createPopup.part_content_set("button1", bt) bt2 = Button(self, text="Cancel") bt2.callback_clicked_add(self.closePopup) self.createPopup.part_content_set("button2", bt2) if defaultPopulate: self.populateFiles(startPath) def folderOnlySet(self, ourValue): self.folderOnly = ourValue if not self.folderOnly: self.filenameBox.show() else: self.filenameBox.hide() def createFolder(self, obj): newDir = "%s%s" % (self.currentDirectory, self.createEn.text) os.makedirs(newDir) self.closePopup() self.populateFiles(self.currentDirectory) def createFolderButtonPressed(self, obj): self.createEn.text = "" self.createPopup.show() self.createEn.select_all() def closePopup(self, btn=None): self.createPopup.hide() def shutdown(self, obj=None): self._timer.delete() self.threadedFunction.shutdown() def sortData(self, btn): self.sortReverse = not self.sortReverse if self.sortReverse: self.fileSortButton.text = u"⬇ Name" else: self.fileSortButton.text = u"⬆ Name" self.populateFiles(self.currentDirectory) def populateBookmarks(self): con = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) con.standard_set("folder_home") con.show() it = self.bookmarksList.item_append("Home", icon=con) it.data["path"] = self.home con = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) con.standard_set("drive-harddisk") con.show() it = self.bookmarksList.item_append("Root", icon=con) it.data["path"] = self.root it = self.bookmarksList.item_append("") it.separator_set(True) for bk in self.getGTKBookmarks(): con = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) con.standard_set("gtk-directory") con.show() it = self.bookmarksList.item_append(bk.split("/")[-1], icon=con) it.data["path"] = bk[7:] def populateFile(self): pen_file = len(self.pendingFiles) if pen_file: for _ in range(int(math.sqrt(pen_file))): ourPath, d, isDir = self.pendingFiles.popleft() self.packFileFolder(ourPath, d, isDir) #else: # self._timer.freeze() return True def populateFiles(self, ourPath): self.autocompleteHover.hover_end() self.pendingFiles.clear() if ourPath[:-1] != "/": ourPath = ourPath + "/" if ourPath != self.filepathEntry.text or not self.showHidden: self.addingHidden = False if self.directoryChangeCallback: self.directoryChangeCallback(ourPath) del self.currentSubFolders[:] del self.currentFiles[:] self.fileList.clear() else: self.addingHidden = True self.filepathEntry.text = ourPath.replace("//", "/") self.currentDirectory = ourPath.replace("//", "/") self.threadedFunction.run(self.getFolderContents) #self._timer.thaw() def getFolderContents(self): ourPath = self.currentDirectory try: data = os.listdir(unicode(ourPath)) except: data = os.listdir(str(ourPath)) sortedData = [] for d in data: isDir = os.path.isdir("%s%s" % (ourPath, d)) if isDir: self.currentSubFolders.append(d) if self.sortReverse: sortedData.append([1, d]) else: sortedData.append([0, d]) else: self.currentFiles.append(d) if self.sortReverse: sortedData.append([0, d]) else: sortedData.append([1, d]) sortedData.sort(reverse=self.sortReverse) for ourFile in sortedData: d = ourFile[1] isDir = ourFile[0] if self.sortReverse else not ourFile[0] if self.addingHidden and d[0] == ".": self.pendingFiles.append([ourPath, d, isDir]) elif (d[0] != "." or self.showHidden) and not self.addingHidden: self.pendingFiles.append([ourPath, d, isDir]) def packFileFolder(self, ourPath, d, isDir): if isDir: li = GenlistItem(item_data={ "type": "dir", "path": ourPath, "d": d }, item_class=dirglic, func=self.listItemSelected) else: li = GenlistItem(item_data={ "type": "file", "path": ourPath, "d": d }, item_class=fileglic, func=self.listItemSelected) li.append_to(self.fileList) #self.fileList.go() #print("Adding: %s %s %s"%(ourPath, d, isDir)) def fileDoubleClicked(self, obj, item=None, eventData=None): if item.data["type"] == "dir": self.addButton.disabled = True self.removeButton.disabled = True self.populateFiles(item.data["path"] + item.text) else: self.actionButtonPressed(self.actionButton) def getGTKBookmarks(self): try: with open(os.path.expanduser('~/.config/gtk-3.0/bookmarks'), 'r') as f: ourBks = [] for x in f: x = x.split(" ")[0] x = x.replace("%20", " ") x = x.strip() ourBks.append(x) return ourBks except IOError: return [] def bookmarkDoubleClicked(self, obj, item=None, eventData=None): item.selected_set(False) self.addButton.disabled = True self.removeButton.disabled = True self.populateFiles(item.data["path"]) def listItemSelected(self, item, gl, data): if item.data["type"] == "dir": self.directorySelected(item) else: self.fileSelected(item.text) item.selected_set(False) def fileSelected(self, ourFile): self.fileEntry.text = ourFile self.addButton.disabled = True self.removeButton.disabled = True self.selectedFolder = None #Update image preview if an image is selected if ourFile[-3:] in ["jpg", "png", "gif"]: self.previewImage.file_set("%s/%s" % (self.filepathEntry.text, ourFile)) self.previewImage.size_hint_weight = (1.0, 0.4) else: self.previewImage.size_hint_weight = (0, 0) def directorySelected(self, btn): ourPath = btn.data["path"] if btn == self.selectedFolder: self.populateFiles(ourPath) self.addButton.disabled = True else: self.selectedFolder = btn currentMarks = self.getGTKBookmarks() toAppend = "file://%s%s" % (self.filepathEntry.text, self.selectedFolder.text) if toAppend not in currentMarks: self.addButton.disabled = False self.removeButton.disabled = True else: self.addButton.disabled = True self.removeButton.disabled = False def upButtonPressed(self, btn): ourSplit = self.filepathEntry.text.split("/") del ourSplit[-1] del ourSplit[-1] self.populateFiles("/".join(ourSplit)) def addButtonPressed(self, btn): toAppend = "file://%s%s" % (self.filepathEntry.text, self.selectedFolder.text.replace( " ", "%20")) con = Icon(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) con.standard_set("gtk-directory") con.show() it = self.bookmarksList.item_append(self.selectedFolder.text, icon=con) it.data["path"] = "%s%s" % (self.filepathEntry.text, self.selectedFolder.text) self.bookmarksList.go() self.addButton.disabled = True self.removeButton.disabled = False with open(os.path.expanduser('~/.config/gtk-3.0/bookmarks'), 'a') as f: f.write(toAppend + " " + self.selectedFolder.text + "\n") def removeButtonPressed(self, btn): toRemove = "file://%s%s" % (self.filepathEntry.text, self.selectedFolder.text) bks = self.getGTKBookmarks() bks.remove(toRemove) with open(os.path.expanduser('~/.config/gtk-3.0/bookmarks'), 'w') as f: for b in bks: bName = b.split("/")[-1] b = b.replace(" ", "%20") f.write(b + " " + bName + "\n") self.bookmarksList.clear() self.populateBookmarks() self.addButton.disabled = False self.removeButton.disabled = True def setMode(self, ourMode): self.mode = ourMode.lower() self.actionButton.text = "%s " % ourMode self.actionIcon.standard_set("document-%s" % ourMode.lower()) if self.mode != "save": self.createFolderButton.hide() else: self.createFolderButton.show() def eventsCb(self, obj, src, event_type, event): if event.modifier_is_set( "Control") and event_type == EVAS_CALLBACK_KEY_DOWN: if event.key.lower() == "l": self.filepathEntry.focus_set(True) self.filepathEntry.cursor_end_set() def toggleHiddenButtonPressed(self, btn): self.showHidden = not self.showHidden self.populateFiles(self.filepathEntry.text) def toggleHidden(self): self.showHidden = not self.showHidden self.populateFiles(self.filepathEntry.text) def callback_cancel_add(self, cb): self.cancelCallback = cb def callback_activated_add(self, cb): self.actionCallback = cb def callback_directory_open_add(self, cb): self.directoryChangeCallback = cb def cancelButtonPressed(self, btn): if self.cancelCallback: self.cancelCallback(self) def actionButtonPressed(self, btn): if self.actionCallback: if not self.folderOnly and self.fileEntry.text: self.actionCallback( self, "%s%s" % (self.filepathEntry.text, self.fileEntry.text)) elif self.folderOnly: self.actionCallback(self, "%s" % (self.filepathEntry.text)) def fileEntryChanged(self, en): typed = en.text.split("/")[-1] newList = [] self.focusedEntry = en if en == self.filepathEntry: for x in self.currentSubFolders: if typed in x: if len(newList) < 10: newList.append(x) else: break else: for x in self.currentFiles: if typed in x: if len(newList) < 10: newList.append(x) else: break if self.autocompleteHover.expanded_get(): self.autocompleteHover.hover_end() self.autocompleteHover.clear() for x in newList: self.autocompleteHover.item_add(x) self.autocompleteHover.hover_begin() def autocompleteSelected(self, hov, item): hov.hover_end() if self.focusedEntry == self.filepathEntry: self.populateFiles("%s%s" % (self.currentDirectory, item.text)) self.filepathEntry.cursor_end_set() else: self.fileEntry.text = item.text self.fileEntry.cursor_end_set() def filepathEditDone(self, en): if os.path.isdir(en.text) and en.text != self.currentDirectory: self.populateFiles(en.text) self.filepathEntry.cursor_end_set() else: #en.text = self.currentDirectory pass def selected_get(self): return "%s%s" % (self.filepathEntry.text, self.fileEntry.text)
class ePadToolbar(Toolbar): def __init__(self, parent, canvas): Toolbar.__init__(self, canvas) self._parent = parent self._canvas = canvas self.homogeneous = False self.size_hint_weight = (0.0, 0.0) self.size_hint_align = (EVAS_HINT_FILL, 0.0) self.select_mode = ELM_OBJECT_SELECT_MODE_NONE self.menu_parent = canvas self.item_append("document-new", "New", self.newPress) self.item_append("document-open", "Open", self.openPress) self.item_append("document-save", "Save", self.savePress) self.item_append("document-save-as", "Save As", self.saveAsPress) # -- Edit Dropdown Menu -- tb_it = self.item_append("edit", "Edit") tb_it.menu = True menu = tb_it.menu menu.item_add(None, "Copy", "edit-copy", self.copyPress) menu.item_add(None, "Paste", "edit-paste", self.pastePress) menu.item_add(None, "Cut", "edit-cut", self.cutPress) menu.item_separator_add() menu.item_add(None, "Select All", "edit-select-all", self.selectAllPress) # ----------------------- # # -- Options Dropdown Menu -- # # self.item_append("settings", "Options", self.optionsPress) tb_it = self.item_append("preferences-desktop", "Options") tb_it.menu = True menu = tb_it.menu self._parent.wordwrap = WORD_WRAP it = menu.item_add(None, "Wordwrap", None, self.optionsWWPress) chk = Check(canvas, disabled=True) it.content = chk # --------------------------- self.item_append("dialog-information", "About", self.aboutPress) def newPress(self, obj, it): self._parent.newFile() def openPress(self, obj, it): self._parent.openFile() def savePress(self, obj, it): self._parent.saveFile() def saveAsPress(self, obj, it): self._parent.saveAs() def optionsWWPress(self, obj, it): wordwrap = self._parent.mainEn.line_wrap wordwrap = not wordwrap self._parent.mainEn.line_wrap = wordwrap it.content.state = wordwrap # FIXME: is this variable needed for anything? self._parent.wordwrap = wordwrap def copyPress(self, obj, it): self._parent.mainEn.selection_copy() def pastePress(self, obj, it): self._parent.mainEn.selection_paste() def cutPress(self, obj, it): self._parent.mainEn.selection_cut() def selectAllPress(self, obj, it): self._parent.mainEn.select_all() def aboutPress(self, obj, it): # About popup self.popupAbout = Popup(self._canvas, size_hint_weight=EXPAND_BOTH) self.popupAbout.part_text_set("title,text", "ePad version {0}".format(__version__)) self.popupAbout.text = ("A simple text editor written in " "python and elementary<br><br> " "By: Jeff Hoogland") bt = Button(self._canvas, text="Done") bt.callback_clicked_add(self.aboutClose) self.popupAbout.part_content_set("button1", bt) self.popupAbout.show() def aboutClose(self, bt): self.popupAbout.delete()
class ePadToolbar(Toolbar): def __init__(self, parent, canvas): Toolbar.__init__(self, canvas) self._parent = parent self._canvas = canvas self.homogeneous = False self.size_hint_weight = (0.0, 0.0) self.size_hint_align = (EVAS_HINT_FILL, 0.0) self.select_mode = ELM_OBJECT_SELECT_MODE_NONE self.menu_parent = canvas self.item_append("document-new", "New", self.newPress) self.item_append("document-open", "Open", self.openPress) self.item_append("document-save", "Save", self.savePress) self.item_append("document-save-as", "Save As", self.saveAsPress) # -- Edit Dropdown Menu -- tb_it = self.item_append("edit", "Edit") tb_it.menu = True menu = tb_it.menu menu.item_add(None, "Copy", "edit-copy", self.copyPress) menu.item_add(None, "Paste", "edit-paste", self.pastePress) menu.item_add(None, "Cut", "edit-cut", self.cutPress) menu.item_separator_add() menu.item_add(None, "Select All", "edit-select-all", self.selectAllPress) # ----------------------- # # -- Options Dropdown Menu -- # # self.item_append("settings", "Options", self.optionsPress) tb_it = self.item_append("preferences-desktop", "Options") tb_it.menu = True menu = tb_it.menu self._parent.wordwrap = WORD_WRAP it = menu.item_add(None, "Wordwrap", None, self.optionsWWPress) chk = Check(canvas, disabled=True) it.content = chk # --------------------------- self.item_append("dialog-information", "About", self.aboutPress) def newPress(self, obj, it): self._parent.newFile() def openPress(self, obj, it): self._parent.openFile() def savePress(self, obj, it): self._parent.saveFile() def saveAsPress(self, obj, it): self._parent.saveAs() def optionsWWPress(self, obj, it): wordwrap = self._parent.mainEn.line_wrap wordwrap = not wordwrap self._parent.mainEn.line_wrap = wordwrap it.content.state = wordwrap # FIXME: is this variable needed for anything? self._parent.wordwrap = wordwrap def copyPress(self, obj, it): self._parent.mainEn.selection_copy() def pastePress(self, obj, it): self._parent.mainEn.selection_paste() def cutPress(self, obj, it): self._parent.mainEn.selection_cut() def selectAllPress(self, obj, it): self._parent.mainEn.select_all() def aboutPress(self, obj, it): # About popup self.popupAbout = Popup(self._canvas, size_hint_weight=EXPAND_BOTH) self.popupAbout.part_text_set("title,text", "ePad version {0}".format(__version__)) self.popupAbout.text = ( "A simple text editor written in " "python and elementary<br><br> " "By: Jeff Hoogland" ) bt = Button(self._canvas, text="Done") bt.callback_clicked_add(self.aboutClose) self.popupAbout.part_content_set("button1", bt) self.popupAbout.show() def aboutClose(self, bt): self.popupAbout.delete()
class Interface(object): def __init__(self): self.mainWindow = StandardWindow("epad", "Untitled - ePad", size=(600, 400)) self.mainWindow.callback_delete_request_add(self.closeChecks) self.mainWindow.elm_event_callback_add(self.eventsCb) icon = Icon(self.mainWindow, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) icon.standard_set('accessories-text-editor') icon.show() self.mainWindow.icon_object_set(icon.object_get()) self.mainBox = Box(self.mainWindow, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.mainBox.show() self.newInstance = NEW_INSTANCE self.mainTb = ePadToolbar(self, self.mainWindow) self.mainTb.focus_allow = False self.mainTb.show() self.mainBox.pack_end(self.mainTb) # Root User Notification if os.geteuid() == 0: printErr("Caution: Root User") if NOTIFY_ROOT: notifyBox = Box(self.mainWindow, horizontal=True) notifyBox.show() notify = Notify(self.mainWindow, size_hint_weight=EXPAND_BOTH, align=(ELM_NOTIFY_ALIGN_FILL, 0.0), content=notifyBox) notifyLabel = Label(self.mainWindow) notifyLabel.text = "<b><i>Root User</i></b>" notifyBox.pack_end(notifyLabel) notifyLabel.show() self.mainBox.pack_end(notifyBox) self.about = aboutWin(self, self.mainWindow) self.about.hide() # Initialize Text entry box and line label # FIXME: self.wordwrap initialized by ePadToolbar print("Word wrap Initialized: {0}".format(self.wordwrap)) self.entryInit() # Build our file selector for saving/loading files self.fileBox = Box(self.mainWindow, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.fileBox.show() self.fileLabel = Label(self.mainWindow, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_BOTH, text="") self.fileLabel.show() self.lastDir = os.getenv("HOME") self.fileSelector = Fileselector(self.mainWindow, is_save=False, expandable=False, folder_only=False, hidden_visible=SHOW_HIDDEN, path=self.lastDir, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.fileSelector.callback_done_add(self.fileSelected) self.fileSelector.callback_activated_add(self.fileSelected) self.fileSelector.callback_directory_open_add(self.updateLastDir) self.fileSelector.path_set(os.getcwd()) self.fileSelector.show() self.fileBox.pack_end(self.fileLabel) self.fileBox.pack_end(self.fileSelector) # Flip object has the file selector on one side # and the GUI on the other self.flip = Flip(self.mainWindow, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.flip.part_content_set("front", self.mainBox) self.flip.part_content_set("back", self.fileBox) self.mainWindow.resize_object_add(self.flip) self.flip.show() self.isSaved = True self.isNewFile = False self.confirmPopup = None self.fileExistsFlag = False def entryInit(self): self.mainEn = Entry(self.mainWindow, scrollable=True, line_wrap=self.wordwrap, autosave=False, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.mainEn.callback_changed_user_add(self.textEdited) self.mainEn.elm_event_callback_add(self.eventsCb) self.mainEn.callback_clicked_add(resetCloseMenuCount) # delete line lable if it exist so we can create and add new one # Later need to rethink logic here try: self.line_label.delete() except AttributeError: pass # Add label to show current cursor position if SHOW_POS: self.line_label = Label(self.mainWindow, size_hint_weight=EXPAND_HORIZ, size_hint_align=ALIGN_RIGHT) self.mainEn.callback_cursor_changed_add(self.curChanged, self.line_label) self.curChanged(self.mainEn, self.line_label) self.line_label.show() self.mainBox.pack_end(self.line_label) # self.mainEn.markup_filter_append(self.textFilter) self.mainEn.show() self.mainEn.focus_set(True) try: self.mainBox.pack_before(self.mainEn, self.line_label) except AttributeError: # line_label has not been initialized on first run # Should have better logic on all this self.mainBox.pack_end(self.mainEn) def curChanged(self, entry, label): # get linear index into current text index = entry.cursor_pos_get() # Replace <br /> tag with single char # to simplify (line, col) calculation tmp_text = markup_to_utf8(entry.entry_get()) line = tmp_text[:index].count("\n") + 1 col = len(tmp_text[:index].split("\n")[-1]) + 1 # Update label text with line, col label.text = "Ln {0} Col {1} ".format(line, col) def textEdited(self, obj): current_file = self.mainEn.file[0] current_file = \ os.path.basename(current_file) if \ current_file and not self.isNewFile else \ "Untitled" self.mainWindow.title = "*%s - ePad" % (current_file) self.isSaved = False def newFile(self, obj=None, ignoreSave=False): if self.newInstance: # sh does not properly handle space between -d and path command = "epad -d'{0}'".format(self.lastDir) print("Launching new instance: {0}".format(command)) ecore.Exe(command, ecore.ECORE_EXE_PIPE_READ | ecore.ECORE_EXE_PIPE_ERROR | ecore.ECORE_EXE_PIPE_WRITE) return if self.isSaved is True or ignoreSave is True: trans = Transit() trans.object_add(self.mainEn) trans.auto_reverse = True trans.effect_wipe_add( ELM_TRANSIT_EFFECT_WIPE_TYPE_HIDE, ELM_TRANSIT_EFFECT_WIPE_DIR_RIGHT) trans.duration = 0.5 trans.go() time.sleep(0.5) self.mainWindow.title_set("Untitled - ePad") self.mainEn.delete() self.entryInit() self.isNewFile = True elif self.confirmPopup is None: self.confirmSave(self.newFile) self.mainEn.focus_set(True) def openFile(self, obj=None, ignoreSave=False): if self.isSaved is True or ignoreSave is True: self.fileSelector.is_save_set(False) self.fileLabel.text = "<b>Select a text file to open:</b>" self.flip.go(ELM_FLIP_ROTATE_YZ_CENTER_AXIS) elif self.confirmPopup is None: self.confirmSave(self.openFile) def confirmSave(self, ourCallback=None): self.confirmPopup = Popup(self.mainWindow, size_hint_weight=EXPAND_BOTH) self.confirmPopup.part_text_set("title,text", "File Unsaved") current_file = self.mainEn.file[0] current_file = \ os.path.basename(current_file) if current_file else "Untitled" self.confirmPopup.text = "Save changes to '%s'?" % (current_file) # Close without saving button no_btt = Button(self.mainWindow) no_btt.text = "No" no_btt.callback_clicked_add(self.closePopup, self.confirmPopup) if ourCallback is not None: no_btt.callback_clicked_add(ourCallback, True) no_btt.show() # cancel close request cancel_btt = Button(self.mainWindow) cancel_btt.text = "Cancel" cancel_btt.callback_clicked_add(self.closePopup, self.confirmPopup) cancel_btt.show() # Save the file and then close button sav_btt = Button(self.mainWindow) sav_btt.text = "Yes" sav_btt.callback_clicked_add(self.saveFile) sav_btt.callback_clicked_add(self.closePopup, self.confirmPopup) sav_btt.show() # add buttons to popup self.confirmPopup.part_content_set("button1", no_btt) self.confirmPopup.part_content_set("button2", cancel_btt) self.confirmPopup.part_content_set("button3", sav_btt) self.confirmPopup.show() def saveAs(self): self.fileSelector.is_save_set(True) self.fileLabel.text = "<b>Save new file to where:</b>" self.flip.go(ELM_FLIP_ROTATE_XZ_CENTER_AXIS) def saveFile(self, obj=False): if self.mainEn.file_get()[0] is None or self.isNewFile: self.saveAs() else: file_selected = self.mainEn.file_get()[0] # Detect save errors as entry.file_save currently returns no errors # even in the case where the file fails to save :( try: newfile = open(file_selected, 'w') except IOError as err: if err.errno == errno.EACCES: errorMsg = ("Permision denied: <b>'%s'</b>." "<br><br>Operation failed !!!" % (file_selected)) errorPopup(self.mainWindow, errorMsg) else: errorMsg = ("ERROR: %s: '%s'" "<br><br>Operation failed !!!" % (err.strerror, file_selected)) errorPopup(self.mainWindow, errorMsg) return newfile.close() # if entry is empty and the file does not exists then # entry.file_save will destroy the file created about by the # open statement above for some odd reason ... if not self.mainEn.is_empty: self.mainEn.file_save() self.mainWindow.title_set("%s - ePad" % os.path.basename(self.mainEn.file[0])) self.isSaved = True def doSelected(self, obj): # Something I should avoid but here I prefer a polymorphic function if isinstance(obj, Button): file_selected = self.fileSelector.selected_get() else: file_selected = obj IsSave = self.fileSelector.is_save_get() if file_selected: if IsSave: try: newfile = open(file_selected, 'w') except IOError as err: print("ERROR: {0}: '{1}'".format(err.strerror, file_selected)) if err.errno == errno.EACCES: errorMsg = ("Permision denied: <b>'%s'</b>." "<br><br>Operation failed !!!</br>" % (file_selected)) errorPopup(self.mainWindow, errorMsg) else: errorMsg = ("ERROR: %s: '%s'" "<br><br>Operation failed !!!</br>" % (err.strerror, file_selected)) errorPopup(self.mainWindow, errorMsg) return tmp_text = self.mainEn.entry_get() # FIXME: Why save twice? newfile.write(tmp_text) newfile.close() # Suppress error message when empty file is saved try: self.mainEn.file_set(file_selected, ELM_TEXT_FORMAT_PLAIN_UTF8) except RuntimeError: print("Empty file saved:{0}".format(file_selected)) self.mainEn.entry_set(tmp_text) # if empty file entry.file_save destroys file :( if len(tmp_text): self.mainEn.file_save() self.mainWindow.title_set("%s - ePad" % os.path.basename(file_selected)) self.isSaved = True self.isNewFile = False else: if os.path.isdir(file_selected): print("ERROR: {0}: is a directory. " "Could not set file.".format(file_selected)) current_file = os.path.basename(file_selected) errorMsg = ("<b>'%s'</b> is a folder." "<br><br>Operation failed !!!</br>" % (current_file)) errorPopup(self.mainWindow, errorMsg) return # Test to see if file can be opened to catch permission errors # as entry.file_set function does not differentiate # different possible errors. try: with open(file_selected) as f: tmp_text = f.readline() except IOError as err: if err.errno == errno.ENOENT: print("Creating New file '{0}'".format(file_selected)) # self.fileSelector.current_name_set(file_selected) self.isSaved = False elif err.errno == errno.EACCES: print("ERROR: {0}: '{1}'".format(err.strerror, file_selected)) errorMsg = ("Permision denied: <b>'%s'</b>." "<br><br>Operation failed !!!</br>" % (file_selected)) errorPopup(self.mainWindow, errorMsg) return else: print("ERROR: {0}: '{1}'".format(err.strerror, file_selected)) errorMsg = ("ERROR: %s: '%s'" "<br><br>Operation failed !!!</br>" % (err.strerror, file_selected)) errorPopup(self.mainWindow, errorMsg) return try: self.mainEn.file_set(file_selected, ELM_TEXT_FORMAT_PLAIN_UTF8) except RuntimeError as msg: # Entry.file_set fails on empty files print("Empty file: {0}".format(file_selected)) self.mainWindow.title_set("%s - ePad" % os.path.basename(file_selected)) self.mainEn.focus_set(True) def fileExists(self, filePath): self.confirmPopup = Popup(self.mainWindow, size_hint_weight=EXPAND_BOTH) # Add a table to hold dialog image and text to Popup tb = Table(self.confirmPopup, size_hint_weight=EXPAND_BOTH) self.confirmPopup.part_content_set("default", tb) tb.show() # Add dialog-error Image to table need_ethumb() icon = Icon(self.confirmPopup, thumb='True') icon.standard_set('dialog-question') # Using gksudo or sudo fails to load Image here # unless options specify using preserving their existing environment. # may also fail to load other icons but does not raise an exception # in that situation. # Works fine using eSudo as a gksudo alternative, # other alternatives not tested try: dialogImage = Image(self.confirmPopup, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_BOTH, file=icon.file_get()) tb.pack(dialogImage, 0, 0, 1, 1) dialogImage.show() except RuntimeError: # An error message is displayed for this same error # when aboutWin is initialized so no need to redisplay. pass # Add dialog text to table dialogLabel = Label(self.confirmPopup, line_wrap=ELM_WRAP_WORD, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_BOTH) current_file = os.path.basename(filePath) dialogLabel.text = "'%s' already exists. Overwrite?<br><br>" \ % (current_file) tb.pack(dialogLabel, 1, 0, 1, 1) dialogLabel.show() # Close without saving button no_btt = Button(self.mainWindow) no_btt.text = "No" no_btt.callback_clicked_add(self.closePopup, self.confirmPopup) no_btt.show() # Save the file and then close button sav_btt = Button(self.mainWindow) sav_btt.text = "Yes" sav_btt.callback_clicked_add(self.doSelected) sav_btt.callback_clicked_add(self.closePopup, self.confirmPopup) sav_btt.show() # add buttons to popup self.confirmPopup.part_content_set("button1", no_btt) self.confirmPopup.part_content_set("button3", sav_btt) self.confirmPopup.show() def fileSelected(self, fs, file_selected, onStartup=False): if not onStartup: self.flip.go(ELM_FLIP_INTERACTION_ROTATE) # Markup can end up in file names because file_selector name_entry # is an elementary entry. So lets sanitize file_selected. file_selected = markup_to_utf8(file_selected) if file_selected: print("File Selected: {0}".format(file_selected)) self.lastDir = os.path.dirname(file_selected) fs.path_set(self.lastDir) # This fails if file_selected does not exist yet try: fs.selected = file_selected except RuntimeError: # FIXME: would be nice if I could set fileSelector name entry pass IsSave = fs.is_save_get() if file_selected: if IsSave: if os.path.isdir(file_selected): current_file = os.path.basename(file_selected) errorMsg = ("<b>'%s'</b> is a folder." "<br><br>Operation failed !!!" % (current_file)) errorPopup(self.mainWindow, errorMsg) return elif os.path.exists(file_selected): self.fileExistsFlag = True self.fileExists(file_selected) return self.doSelected(file_selected) def updateLastDir(self, fs, path): self.lastDir = path def closeChecks(self, obj): print("File is Saved: ", self.isSaved) if not self.flip.front_visible_get(): self.flip.go(ELM_FLIP_ROTATE_XZ_CENTER_AXIS) elif self.isSaved is False and self.confirmPopup is None: self.confirmSave(self.closeApp) else: self.closeApp() def closePopup(self, bt, confirmPopup): self.confirmPopup.delete() self.confirmPopup = None def showAbout(self): self.about.launch() def closeApp(self, obj=False, trash=False): elementary.exit() def eventsCb(self, obj, src, event_type, event): if event.modifier_is_set("Control"): if event.key.lower() == "n": self.newFile() elif event.key.lower() == "s" and event.modifier_is_set("Shift"): self.saveAs() elif event.key.lower() == "s": self.saveFile() elif event.key.lower() == "o": self.openFile() elif event.key.lower() == "h": if not self.flip.front_visible_get(): toggleHidden(self.fileSelector) elif event.key.lower() == "q": closeCtrlChecks(self) # Legacy hack no longer needed # there was an issue in elementary entry where it would # accept those character controls # def textFilter( self, obj, theText, data ): # # Block ctrl+hot keys used in eventsCb # # # # Ctrl O Ctrl N Ctrl S # ctrl_block = [chr(14), chr(15), chr(19)] # if theText in ctrl_block: # return None # else: # return theText def launch(self, start=[]): if start and start[0] and os.path.dirname(start[0]) == '': start[0] = os.getcwd() + '/' + start[0] if start and start[0]: if os.path.isdir(os.path.dirname(start[0])): self.fileSelected(self.fileSelector, start[0], True) else: print("Error: {0} is an Invalid Path".format(start)) errorMsg = ("<b>'%s'</b> is an Invalid path." "<br><br>Open failed !!!" % (start)) errorPopup(self.mainWindow, errorMsg) if start and start[1]: if os.path.isdir(start[1]): print("Initializing file selection path: {0}".format(start[1])) self.fileSelector.path_set(start[1]) self.lastDir = start[1] else: print("Error: {0} is an Invalid Path".format(start[1])) self.mainWindow.show()