diff options
author | toma <toma@283d02a7-25f6-0310-bc7c-ecb5cbfe19da> | 2009-11-25 17:56:58 +0000 |
---|---|---|
committer | toma <toma@283d02a7-25f6-0310-bc7c-ecb5cbfe19da> | 2009-11-25 17:56:58 +0000 |
commit | 90825e2392b2d70e43c7a25b8a3752299a933894 (patch) | |
tree | e33aa27f02b74604afbfd0ea4f1cfca8833d882a /korundum/rubylib/examples | |
download | tdebindings-90825e2392b2d70e43c7a25b8a3752299a933894.tar.gz tdebindings-90825e2392b2d70e43c7a25b8a3752299a933894.zip |
Copy the KDE 3.5 branch to branches/trinity for new KDE 3.5 features.
BUG:215923
git-svn-id: svn://anonsvn.kde.org/home/kde/branches/trinity/kdebindings@1054174 283d02a7-25f6-0310-bc7c-ecb5cbfe19da
Diffstat (limited to 'korundum/rubylib/examples')
28 files changed, 5282 insertions, 0 deletions
diff --git a/korundum/rubylib/examples/RubberDoc.rb b/korundum/rubylib/examples/RubberDoc.rb new file mode 100755 index 00000000..604a9492 --- /dev/null +++ b/korundum/rubylib/examples/RubberDoc.rb @@ -0,0 +1,1265 @@ +#!/usr/bin/env ruby + +require 'Korundum' + +about = KDE::AboutData.new("one", "two", "three") +KDE::CmdLineArgs.init(ARGV, about) +app = KDE::Application.new() + +# Qt.debug_level = Qt::DebugLevel::High +# Qt.debug_level = Qt::DebugLevel::Extensive + +# TODO +# improve appearence of sidebar massively +# cut off after certain number of results? +# seperate title from proof of hit? +# when pressing return adjust the current node +# major speed ups for ctrl-n/p +# ... + +DEBUG = false +DEBUG_IDX = false +DEBUG_FAST = true +DEBUG_SEARCH = true +DEBUG_GOTO = false # crashes? + +def time_me str + t1 = Time.now + yield + t2 = Time.now + log "#{str}: #{"%.02f" % (t2 - t1).to_f}s" +end + +module DOMUtils + + def DOMUtils.each_child node + indent = 0 + until node.isNull + yield node + if not node.firstChild.isNull + node = node.firstChild + indent += 1 + elsif not node.nextSibling.isNull + node = node.nextSibling + else + while indent > 0 and !node.isNull and node.nextSibling.isNull + node = node.parentNode + indent -= 1 + end + if not node.isNull + node = node.nextSibling + end + end + break if indent == 0 + end + end + + def DOMUtils.find_node doc, path_a + n = doc + path_a.reverse.each { + |index| + top = n.childNodes.length + n = n.childNodes.item (top - index) + } + n + end + + def DOMUtils.each_parent node + n = node + until n.isNull + yield n + n = n.parentNode + end + end + + def DOMUtils.list_parent_node_types node + types_a = [] + each_parent(node) { + |n| types_a << { :nodeType => n.nodeType, :elementId => n.elementId } + } + types_a + end + + def DOMUtils.get_node_path node + n = node + path_a = [] + until n.isNull + top = n.parentNode.childNodes.length + idx = n.index + path_a << (top-idx) if (n.elementId != 0) + n = n.parentNode + end + path_a + end + +end + +class String + def trigrams + list = [] + 0.upto(self.length-3) { + |pos| + list << self.slice(pos, 3) + } + list + end +end + +class GenericTriGramIndex + attr_accessor :trigrams + + def initialize + clear + end + + def clear + @trigrams = {} + end + + def insert_with_key string, key + string.downcase.trigrams.each { + |trigram| + @trigrams[trigram] = [] unless @trigrams.has_key? trigram + @trigrams[trigram] << key + } + end + + # returns a list of matching keys + def search search_string + warn "searching for a nil???" if search_string.nil? + return [] if search_string.nil? + return [] if search_string.length < 3 + trigs = search_string.downcase.trigrams + key_subset = @trigrams[trigs.delete_at(0)] + return [] if key_subset.nil? + trigs.each { + |trigram| + trigram_subset = @trigrams[trigram] + return [] if trigram_subset.nil? + key_subset &= trigram_subset + } + key_subset + end +end + +module LoggedDebug + + def init_logger parent + @logger = Qt::TextEdit.new parent + @logger.setTextFormat Qt::LogText + end + + def log s + @logger.append s + puts "LOG: #{s}" + scrolldown_logger + end + + def scrolldown_logger + @logger.scrollToBottom + end + +end + +module MyGui + + def init_gui + buttons = Qt::HBox.new self + @panes = Qt::Splitter.new self + @panes.setOrientation Qt::Splitter::Horizontal + setStretchFactor @panes, 10 + + @results_pane = Qt::VBox.new @panes + + @rightpane = Qt::Splitter.new @panes + @rightpane.setOrientation Qt::Splitter::Vertical + @viewed = KDE::HTMLPart.new @rightpane + init_logger @rightpane + + @listbox = Qt::ListBox.new @results_pane + + @label = Qt::Label.new self + + Qt::Object.connect @listbox, SIGNAL("clicked(QListBoxItem*)"), + self, SLOT("clicked_result(QListBoxItem*)") + Qt::Object.connect @viewed, SIGNAL("completed()"), + self, SLOT("khtml_part_init_complete()") + + Qt::Object::connect @viewed, SIGNAL("setWindowCaption(const QString&)"), + @viewed.widget.topLevelWidget, + SLOT("setCaption(const QString&)") + + Qt::Object::connect @viewed.browserExtension, + SIGNAL("openURLRequest(const KURL&, const KParts::URLArgs&)"), + self, SLOT("open_url(const KURL&)") + + KDE::Action.new "&Quit", "quit", KDE::Shortcut.new(), + self, SLOT("quit()"), @main.actionCollection, "file_quit" + KDE::Action.new "&Index-All", KDE::Shortcut.new(), + self, SLOT("index_all()"), @main.actionCollection, "index_all" + @back = \ + KDE::Action.new "&Back", "back", KDE::Shortcut.new(Qt::ALT + Qt::Key_Left), + self, SLOT("go_back()"), @main.actionCollection, "back" + @forward = \ + KDE::Action.new "&Forward", "forward", KDE::Shortcut.new(Qt::ALT + Qt::Key_Right), + self, SLOT("go_forward()"), @main.actionCollection, "forward" + KDE::Action.new "&Home", "gohome", KDE::Shortcut.new(Qt::Key_Home), + self, SLOT("go_home()"), @main.actionCollection, "home" + KDE::Action.new "&Prev Match", "previous",KDE::Shortcut.new(Qt::CTRL + Qt::Key_P), + self, SLOT("goto_prev_match()"), @main.actionCollection, "prev_match" + KDE::Action.new "&Next Match", "next", KDE::Shortcut.new(Qt::CTRL + Qt::Key_N), + self, SLOT("goto_next_match()"), @main.actionCollection, "next_match" + KDE::Action.new "&Follow Match","down", KDE::Shortcut.new(Qt::Key_Return), + self, SLOT("goto_current_match_link()"), @main.actionCollection, "open_match" + + KDE::Action.new "Search", "find", KDE::Shortcut.new(Qt::Key_F6), + self, SLOT("focus_search()"), @main.actionCollection, "focus_search" + KDE::Action.new "New Search", "find", KDE::Shortcut.new(Qt::CTRL + Qt::Key_Slash), + self, SLOT("focus_and_clear_search()"), @main.actionCollection, "focus_and_clear_search" + + KDE::Action.new "&Create", "new", KDE::Shortcut.new(), + self, SLOT("project_create()"), @main.actionCollection, "project_create" + KDE::Action.new "&Choose...", "select", KDE::Shortcut.new(), + self, SLOT("project_goto()"), @main.actionCollection, "project_goto" + + clearLocation = KDE::Action.new "Clear Location Bar", "locationbar_erase", KDE::Shortcut.new(), + self, SLOT("clear_location()"), @main.actionCollection, "clear_location" + clearLocation.setWhatsThis "Clear Location bar<p>Clears the content of the location bar." + + @searchlabel = Qt::Label.new @main + @searchlabel.setText "Search: " + + @searchcombo = KDE::HistoryCombo.new @main + focus_search + Qt::Object.connect @searchcombo, SIGNAL("returnPressed()"), + self, SLOT("goto_search()") + Qt::Object.connect @searchcombo, SIGNAL("textChanged(const QString&)"), + self, SLOT("search(const QString&)") + + KDE::WidgetAction.new @searchlabel, "Search: ", KDE::Shortcut.new(Qt::Key_F6), nil, nil, @main.actionCollection, "location_label" + @searchlabel.setBuddy @searchcombo + + ca = KDE::WidgetAction.new @searchcombo, "Search", KDE::Shortcut.new, nil, nil, @main.actionCollection, "toolbar_url_combo" + ca.setAutoSized true + Qt::WhatsThis::add @searchcombo, "Search<p>Enter a search term." + end + + def focus_search + @searchcombo.setFocus + end + + def focus_and_clear_search + clear_location + focus_search + end + + def clear_location + @searchcombo.clearEdit + end + + def uri_anchor_split url + url =~ /(.*?)(#(.*))?$/ + return $1, $3 + end + + def open_url kurl + url, anchor = uri_anchor_split kurl.url + goto_url url, false unless id == @shown_doc_id + @viewed.gotoAnchor anchor unless anchor.nil? + end + + def gui_init_proportions + # todo - save these settings + desktop = Qt::Application::desktop + sx = (desktop.width * (2.0/3.0)).to_i + sy = (desktop.height * (2.0/3.0)).to_i + + @main.resize sx, sy + + logsize = 0 + resultssize = (sx / 5.0).to_i + + @rightpane.setSizes [sy-logsize, logsize] + @panes.setSizes [resultssize, sx-resultssize] + + @rightpane.setResizeMode @logger, Qt::Splitter::KeepSize + + @panes.setResizeMode @results_pane, Qt::Splitter::KeepSize + @panes.setResizeMode @rightpane, Qt::Splitter::KeepSize + end + +end + +module IndexStorage + + INDEX_VERSION = 3 + + IndexStore = Struct.new :index, :nodeindex, :textcache, :id2title, :id2uri, :id2depth, :version + + def index_fname + basedir = ENV["HOME"] + "/.rubberdocs" + prefix = basedir + "/." + @pref.gsub(/\//,",") + ".idx" + Dir.mkdir basedir unless File.exists? basedir + "#{prefix}.doc" + end + + def depth_debug + puts "depth_debug : begin" + @id2depth.each_key { + |id| + puts "indexed to depth #{@id2depth[id]} : #{@id2uri[id]}" + } + puts "end :" + end + + def load_indexes + return false unless File.exists? index_fname + Qt::Application::setOverrideCursor(Qt::Cursor.new Qt::WaitCursor) + File.open(index_fname, "r") { + |file| + w = Marshal.load file rescue nil + return false if w.nil? || w.version < INDEX_VERSION + @index = w.index + @nodeindex = w.nodeindex + @textcache = w.textcache + @id2title = w.id2title + @id2uri = w.id2uri + @id2depth = w.id2depth + @indexed_more = false + true + } + Qt::Application::restoreOverrideCursor + end + + def save_indexes + return unless @indexed_more + File.open(index_fname, "w") { + |file| + w = IndexStore.new + w.index = @index + w.nodeindex = @nodeindex + w.textcache = @textcache + w.id2title = @id2title + w.id2uri = @id2uri + w.id2depth = @id2depth + w.version = INDEX_VERSION + Marshal.dump w, file + } + end + +end + +module HTMLIndexer + + DocNodeRef = Struct.new :doc_idx, :node_path + + module IndexDepths + # TitleIndexed implies "LinkTitlesIndexed" + Allocated, TitleIndexed, LinksFollowed, Partial, Node = 0, 1, 2, 3, 4 + end + + def index_documents + # fix this to use kde's actual dir + @t1 = Time.now + @url = first_url + already_indexed = load_indexes + @top_doc_id = already_indexed ? @id2uri.keys.max + 1 : 0 + return if already_indexed + t1 = Time.now + @viewed.hide + @done = [] + @todo_links = [] + progress = KDE::ProgressDialog.new(self, "blah", "Indexing files...", "Abort Indexing", true) + total_num_files = Dir.glob("#{@pref}/**/*.html").length + progress.progressBar.setTotalSteps total_num_files + @todo_links = [ DOM::DOMString.new first_url.url ] + until @todo_links.empty? + @todo_next = [] + while more_to_do + progress.progressBar.setProgress @id2title.keys.length + end + @todo_links = @todo_next + fail "errr, you really didn't want to do that dave" if progress.wasCancelled + end + progress.progressBar.setProgress total_num_files + save_indexes + t2 = Time.now + log "all documents indexed in #{(t2 - t1).to_i}s" + end + + def should_follow? lhref + case lhref + when /source/, /members/ + ret = false + when /^file:#{@pref}/ + ret = true + else + ret = false + end + ret + end + + def gather_for_current_page + index_current_title + return [] if @id2depth[@shown_doc_id] >= IndexDepths::LinksFollowed + todo_links = [] + title_map = {} + anchors = @viewed.htmlDocument.links + f = anchors.firstItem + count = anchors.length + until (count -= 1) < 0 + text = "" + DOMUtils.each_child(f) { + |node| + text << node.nodeValue.string if node.nodeType == DOM::Node::TEXT_NODE + } + link = Qt::Internal::cast_object_to f, DOM::HTMLLinkElement + if should_follow? link.href.string + title_map[link.href.string] = text + urlonly, = uri_anchor_split link.href.string + add_link_to_index urlonly, text + todo_links << link.href unless DEBUG_FAST + end + f = anchors.nextItem + end + @id2depth[@shown_doc_id] = IndexDepths::LinksFollowed + return todo_links + end + + def find_allocated_uri uri + id = @id2uri.invert[uri] + return id + end + + # sets @shown_doc_id + def index_current_title + id = find_allocated_uri(@viewed.htmlDocument.URL.string) + return if !id.nil? and @id2depth[id] >= IndexDepths::TitleIndexed + log "making space for url #{@viewed.htmlDocument.URL.string.sub(@pref,"")}" + id = alloc_index_space @viewed.htmlDocument.URL.string if id.nil? + @indexed_more = true + @id2title[id] = @viewed.htmlDocument.title.string + @id2depth[id] = IndexDepths::TitleIndexed + @shown_doc_id = id + end + + def alloc_index_space uri + @indexed_more = true + id = @top_doc_id + @id2uri[@top_doc_id] = uri + @id2title[@top_doc_id] = nil + @id2depth[@top_doc_id] = IndexDepths::Allocated + @top_doc_id += 1 + id + end + + def add_link_to_index uri, title + return unless find_allocated_uri(uri).nil? + @indexed_more = true + new_id = alloc_index_space uri + @id2title[new_id] = title + @index.insert_with_key title, new_id + end + + def index_current_document + return if @id2depth[@shown_doc_id] >= IndexDepths::Partial + Qt::Application::setOverrideCursor(Qt::Cursor.new Qt::WaitCursor) + @indexed_more = true + @label.setText "Scanning : #{@url.prettyURL}" + log "indexing url #{@viewed.htmlDocument.URL.string.sub(@pref,"")}" + DOMUtils.each_child(@viewed.document) { + |node| + next unless node.nodeType == DOM::Node::TEXT_NODE + @index.insert_with_key node.nodeValue.string, @shown_doc_id + } + @id2depth[@shown_doc_id] = IndexDepths::Partial + @label.setText "Ready" + Qt::Application::restoreOverrideCursor + end + + def preload_text + return if @id2depth[@shown_doc_id] >= IndexDepths::Node + Qt::Application::setOverrideCursor(Qt::Cursor.new Qt::WaitCursor) + @indexed_more = true + index_current_document + log "deep indexing url #{@viewed.htmlDocument.URL.string.sub(@pref,"")}" + @label.setText "Indexing : #{@url.prettyURL}" + doc_text = "" + t1 = Time.now + DOMUtils.each_child(@viewed.document) { + |node| + next unless node.nodeType == DOM::Node::TEXT_NODE + ref = DocNodeRef.new @shown_doc_id, DOMUtils.get_node_path(node) + @nodeindex.insert_with_key node.nodeValue.string, ref + @textcache[ref] = node.nodeValue.string + doc_text << node.nodeValue.string + } + @id2depth[@shown_doc_id] = IndexDepths::Node + @label.setText "Ready" + Qt::Application::restoreOverrideCursor + end + +end + +# TODO - this sucks, use khtml to get the values +module IDS + A = 1 + META = 62 + STYLE = 85 + TITLE = 95 +end + +module TermHighlighter + + include IDS + + FORBIDDEN_TAGS = [IDS::TITLE, IDS::META, IDS::STYLE] + + def update_highlight + return if @search_text.nil? || @search_text.empty? + return if @in_update_highlight + @in_update_highlight = true + preload_text + highlighted_nodes = [] + @nodeindex.search(@search_text).each { + |ref| + next unless ref.doc_idx == @shown_doc_id + highlighted_nodes << ref.node_path + } + highlight_node_list highlighted_nodes + @in_update_highlight = false + end + + def mark_screwup + @screwups = 0 if @screwups.nil? + warn "if you see this, then alex screwed up!.... #{@screwups} times!" + @screwups += 1 + end + + def highlight_node_list highlighted_nodes + doc = @viewed.document + no_undo_buffer = @to_undo.nil? + current_doc_already_highlighted = (@shown_doc_id == @last_highlighted_doc_id) + undo_highlight @to_undo unless no_undo_buffer or !current_doc_already_highlighted + @last_highlighted_doc_id = @shown_doc_id + @to_undo = [] + return if highlighted_nodes.empty? + Qt::Application::setOverrideCursor(Qt::Cursor.new Qt::WaitCursor) + cursor_override = true + @current_matching_node_index = 0 if @current_matching_node_index.nil? + @current_matching_node_index = @current_matching_node_index.modulo highlighted_nodes.length + caretnode = DOMUtils.find_node doc, highlighted_nodes[@current_matching_node_index] + @viewed.setCaretVisible false + @viewed.setCaretPosition caretnode, 0 + caret_path = DOMUtils.get_node_path(caretnode) + count = 0 + @skipped_highlight_requests = false + @current_matched_href = nil + highlighted_nodes.sort.each { + |path| + node = DOMUtils.find_node doc, path + next mark_screwup if node.nodeValue.string.nil? + match_idx = node.nodeValue.string.downcase.index @search_text.downcase + next mark_screwup if match_idx.nil? + parent_info = DOMUtils.list_parent_node_types node + has_title_parent = !(parent_info.detect { |a| FORBIDDEN_TAGS.include? a[:elementId] }.nil?) + next if has_title_parent + if path == caret_path + DOMUtils.each_parent(node) { + |n| + next unless n.elementId == IDS::A + # link = DOM::HTMLLinkElement.new n # WTF? why doesn't this work??? + link = Qt::Internal::cast_object_to n, "DOM::HTMLLinkElement" + @current_matched_href = link.href.string + } + end + before = doc.createTextNode node.nodeValue.split(0) + matched = doc.createTextNode before.nodeValue.split(match_idx) + after = doc.createTextNode matched.nodeValue.split(@search_text.length) + DOM::CharacterData.new(DOM::Node.new after).setData DOM::DOMString.new("") \ + if after.nodeValue.string.nil? + span = doc.createElement DOM::DOMString.new("span") + spanelt = DOM::HTMLElement.new span + classname = (path == caret_path) ? "foundword" : "searchword" + spanelt.setClassName DOM::DOMString.new(classname) + span.appendChild matched + node.parentNode.insertBefore before, node + node.parentNode.insertBefore span, node + node.parentNode.insertBefore after, node + @to_undo << [node.parentNode, before] + node.parentNode.removeChild node + rate = (count > 50) ? 50 : 10 + allow_user_input = ((count+=1) % rate == 0) + if allow_user_input + Qt::Application::restoreOverrideCursor if cursor_override + cursor_override = false + @in_node_highlight = true + Qt::Application::eventLoop.processEvents Qt::EventLoop::AllEvents, 10 + @in_node_highlight = false + if @skipped_highlight_requests + @timer.start 50, true + return false + end + @viewed.view.layout + end + } + if @skipped_highlight_requests + @timer.start 50, true + end + Qt::Application::restoreOverrideCursor if cursor_override + end + + def undo_highlight to_undo + to_undo.reverse.each { + |pnn| pn, before = *pnn + mid = before.nextSibling + after = mid.nextSibling + beforetext = before.nodeValue + aftertext = after.nodeValue + pn.removeChild after + midtxtnode = mid.childNodes.item(0) + midtext = midtxtnode.nodeValue + str = DOM::DOMString.new "" + str.insert aftertext, 0 + str.insert midtext, 0 + str.insert beforetext, 0 + chardata = DOM::CharacterData.new(DOM::Node.new before) + chardata.setData str + pn.removeChild mid + } + end + +end + +class SmallIconSet + def SmallIconSet.[] name + loader = KDE::Global::instance.iconLoader + return loader.loadIconSet name, KDE::Icon::Small, 0 + end +end + +class ProjectEditDialog < Qt::Object + + slots "select_file()", "slot_ok()" + + def initialize project_name, parent=nil,name=nil,caption=nil + + super(parent, name) + @parent = parent + + @dialog = KDE::DialogBase.new(parent,name, true, caption, + KDE::DialogBase::Ok|KDE::DialogBase::Cancel, KDE::DialogBase::Ok, false) + + vbox = Qt::VBox.new @dialog + + grid = Qt::Grid.new 2, Qt::Horizontal, vbox + + titlelabel = Qt::Label.new "Name:", grid + @title = KDE::LineEdit.new grid + titlelabel.setBuddy @title + + urllabel = Qt::Label.new "Location:", grid + lochbox = Qt::HBox.new grid + @url = KDE::LineEdit.new lochbox + urllabel.setBuddy @url + locselc = Qt::PushButton.new lochbox + locselc.setIconSet SmallIconSet["up"] + + blub = Qt::HBox.new vbox + Qt::Label.new "Is main one?:", blub + @cb = Qt::CheckBox.new blub + + enabled = @parent.projects_data.project_list.empty? + + unless project_name.nil? + project_url = @parent.projects_data.project_list[project_name] + @title.setText project_name + @url.setText project_url + enabled = true if (project_name == @parent.projects_data.enabled_name) + end + + @cb.setChecked true if enabled + + Qt::Object.connect @dialog, SIGNAL("okClicked()"), + self, SLOT("slot_ok()") + + Qt::Object.connect locselc, SIGNAL("clicked()"), + self, SLOT("select_file()") + + @title.setFocus + + @dialog.setMainWidget vbox + + @modified = false + end + + def select_file + s = Qt::FileDialog::getOpenFileName ENV["HOME"], "HTML Files (*.html)", + @parent, "open file dialog", "Choose a file" + @url.setText s unless s.nil? + end + + def edit + @dialog.exec + return @modified + end + + def new_name + @title.text + end + + def new_url + @url.text + end + + def new_enabled + @cb.isChecked + end + + def slot_ok + @parent.projects_data.project_list[new_name] = new_url + @parent.projects_data.enabled_name = new_name if new_enabled + @modified = true + end + +end + +class ProjectSelectDialog < Qt::Object + + slots "edit_selected_project()", "delete_selected_project()", "project_create_button()", "project_selected()" + + def initialize parent=nil,name=nil,caption=nil + super(parent, name) + @parent = parent + + @dialog = KDE::DialogBase.new parent,name, true, caption, + KDE::DialogBase::Ok|KDE::DialogBase::Cancel, KDE::DialogBase::Ok, false + + vbox = Qt::VBox.new @dialog + + @listbox = Qt::ListBox.new vbox + + fill_listbox + + hbox = Qt::HBox.new vbox + button_new = Qt::PushButton.new "New...", hbox + button_del = Qt::PushButton.new "Delete", hbox + button_edit = Qt::PushButton.new "Edit...", hbox + + Qt::Object.connect button_new, SIGNAL("clicked()"), + self, SLOT("project_create_button()") + + Qt::Object.connect button_del, SIGNAL("clicked()"), + self, SLOT("delete_selected_project()") + + Qt::Object.connect button_edit, SIGNAL("clicked()"), + self, SLOT("edit_selected_project()") + + Qt::Object.connect @listbox, SIGNAL("doubleClicked(QListBoxItem *)"), + self, SLOT("project_selected()") + + @dialog.setMainWidget vbox + end + + def project_selected + return if @listbox.selectedItem.nil? + @parent.current_project_name = @listbox.selectedItem.text + @parent.blah_blah + @dialog.reject + end + + def fill_listbox + @listbox.clear + @parent.projects_data.project_list.keys.each { + |name| + enabled = (name == @parent.projects_data.enabled_name) + icon = enabled ? "forward" : "down" + pm = SmallIconSet[icon].pixmap(Qt::IconSet::Automatic, Qt::IconSet::Normal) + it = Qt::ListBoxPixmap.new pm, name + @listbox.insertItem it + } + end + + def edit_selected_project + return if @listbox.selectedItem.nil? + oldname = @listbox.selectedItem.text + dialog = ProjectEditDialog.new oldname, @parent + mod = dialog.edit + if mod and oldname != dialog.new_name + @parent.projects_data.project_list.delete oldname + end + fill_listbox if mod + end + + def project_create_button + mod = @parent.project_create + fill_listbox if mod + end + + def delete_selected_project + return if @listbox.selectedItem.nil? + # TODO - confirmation dialog + @parent.projects_data.project_list.delete @listbox.selectedItem.text + fill_listbox + end + + def select + @dialog.exec + end + +end + +module ProjectManager + + def project_create + dialog = ProjectEditDialog.new nil, self + dialog.edit + while @projects_data.project_list.empty? + dialog.edit + end + end + + def project_goto + dialog = ProjectSelectDialog.new self + dialog.select + if @projects_data.project_list.empty? + project_create + end + end + + require 'yaml' + + def yamlfname + ENV["HOME"] + "/.rubberdocs/projects.yaml" + end + + PROJECT_STORE_VERSION = 0 + + Projects = Struct.new :project_list, :enabled_name, :version + + def load_projects + okay = false + if File.exists? yamlfname + @projects_data = YAML::load File.open(yamlfname) + if (@projects_data.version rescue -1) >= PROJECT_STORE_VERSION + okay = true + end + end + if not okay or @projects_data.project_list.empty? + @projects_data = Projects.new({}, nil, PROJECT_STORE_VERSION) + project_create + end + if @projects_data.enabled_name.nil? + @projects_data.enabled_name = @projects_data.project_list.keys.first + end + end + + def save_projects + File.open(yamlfname, "w+") { + |file| + file.puts @projects_data.to_yaml + } + end + +end + +class RubberDoc < Qt::VBox + + slots "khtml_part_init_complete()", + "go_back()", "go_forward()", "go_home()", "goto_url()", + "goto_search()", "clicked_result(QListBoxItem*)", + "search(const QString&)", "update_highlight()", + "quit()", "open_url(const KURL&)", "index_all()", + "goto_prev_match()", "goto_next_match()", "clear_location()", "activated()", + "goto_current_match_link()", "focus_search()", "focus_and_clear_search()", + "project_create()", "project_goto()" + + attr_accessor :back, :forward, :url, :projects_data + + include LoggedDebug + include MyGui + include IndexStorage + include HTMLIndexer + include TermHighlighter + include ProjectManager + + def init_blah + @index = GenericTriGramIndex.new + @nodeindex = GenericTriGramIndex.new + @textcache = {} + @id2uri, @id2title, @id2depth = {}, {}, {} + + @history, @popped_history = [], [] + @shown_doc_id = 0 + @freq_sorted_idxs = nil + @last_highlighted_doc_id, @to_undo = nil, nil, nil + @search_text = nil + @current_matched_href = nil + + @in_update_highlight = false + @in_node_highlight = false + + @lvis = nil + end + + def initialize parent + super parent + @main = parent + + load_projects + @current_project_name = @projects_data.enabled_name + + init_blah + + init_gui + gui_init_proportions + + @timer = Qt::Timer.new self + Qt::Object.connect @timer, SIGNAL("timeout()"), + self, SLOT("update_highlight()") + + @viewed.openURL KDE::URL.new("about:blank") + + @init_connected = true + end + + def blah_blah + save_indexes + init_blah + khtml_part_init_complete + end + + def quit + @main.close + end + + def khtml_part_init_complete + Qt::Object.disconnect @viewed, SIGNAL("completed()"), + self, SLOT("khtml_part_init_complete()") if @init_connected + + @pref = File.dirname first_url.url.gsub("file:","") + + init_khtml_part_settings @viewed if @init_connected + index_documents + + # maybe make a better choice as to the start page??? + @shown_doc_id = 0 + goto_url @id2uri[@shown_doc_id], false + + @viewed.show + + search "qlistview" if DEBUG_SEARCH || DEBUG_GOTO + goto_search if DEBUG_GOTO + + @init_connected = false + end + + def finish + save_projects + save_indexes + end + + def init_khtml_part_settings khtmlpart + khtmlpart.setJScriptEnabled true + khtmlpart.setJavaEnabled false + khtmlpart.setPluginsEnabled false + khtmlpart.setAutoloadImages false + end + + def load_page + @viewed.setCaretMode true + @viewed.setCaretVisible false + @viewed.document.setAsync false + @viewed.document.load DOM::DOMString.new @url.url + @viewed.setUserStyleSheet "span.searchword { background-color: yellow } + span.foundword { background-color: green }" + Qt::Application::eventLoop.processEvents Qt::EventLoop::ExcludeUserInput + end + + attr_accessor :current_project_name + + def first_url + return KDE::URL.new @projects_data.project_list[@current_project_name] + end + + def search s + if @in_node_highlight + @skipped_highlight_requests = true + return + end + puts "search request: #{s}" + @search_text = s + + results = @index.search(s) + results += @nodeindex.search(s).collect { |docref| docref.doc_idx } + + idx_hash = Hash.new { |h,k| h[k] = 0 } + results.each { + |idx| idx_hash[idx] += 1 + } + @freq_sorted_idxs = idx_hash.to_a.sort_by { |val| val[1] }.reverse + + update_lv + + hl_timeout = 150 # continuation search should be slower? + @timer.start hl_timeout, true unless @freq_sorted_idxs.empty? + end + + def look_for_prefixes + prefixes = [] + # TODO - fix this crappy hack + @id2title.values.compact.sort.each { + |title| + title.gsub! "\n", "" + pos = title.index ":" + next if pos.nil? + prefix = title[0..pos-1] + prefixes << prefix + new_title = title[pos+1..title.length] + new_title.gsub! /(\s\s+|^\s+|\s+$)/, "" + title.replace new_title + } + end + + class ResultItem < Qt::ListBoxItem + def initialize header, text + super() + @text, @header = text, header + @font = Qt::Font.new("Helvetica", 8) + @flags = Qt::AlignLeft | Qt::WordBreak + end + def paint painter + w, h = width(listBox), height(listBox) + header_height = (text_height @font, @header) + 5 + painter.setFont @font + painter.fillRect 5, 5, w - 10, header_height, Qt::Brush.new(Qt::Color.new 150,100,150) + painter.drawText 5, 5, w - 10, header_height, @flags, @header + painter.fillRect 5, header_height, w - 10, h - 10, Qt::Brush.new(Qt::Color.new 100,150,150) + painter.setFont @font + painter.drawText 5, header_height + 2, w - 10, h - 10, @flags, @text + end + def text_height font, text + fm = Qt::FontMetrics.new font + br = fm.boundingRect 0, 0, width(listBox) - 20, 8192, @flags, text + br.height + end + def height listbox + h = 0 + h += text_height @font, @text + h += text_height @font, @header + return h + 10 + end + def width listbox + listBox.width - 5 + end + end + + CUTOFF = 100 + def update_lv + @listbox.clear + @lvis = {} + look_for_prefixes + return if @freq_sorted_idxs.nil? + @freq_sorted_idxs.each { + |a| idx, count = *a + title = @id2title[idx] + # we must re-search until we have a doc -> nodes list + matches_text = "" + @nodeindex.search(@search_text).each { + |ref| + break if matches_text.length > CUTOFF + next unless ref.doc_idx == idx + matches_text << @textcache[ref] << "\n" + } + matches_text = matches_text.slice 0..CUTOFF + lvi = ResultItem.new "(#{count}) #{title}", matches_text + @listbox.insertItem lvi + @lvis[lvi] = idx + } + end + + def goto_search + idx, count = *(@freq_sorted_idxs.first) + goto_id_and_hl idx + end + + def clicked_result i + return if i.nil? + idx = @lvis[i] + goto_id_and_hl idx + end + + def goto_id_and_hl idx + @current_matching_node_index = 0 + goto_url @id2uri[idx], true + @shown_doc_id = idx + update_highlight + end + + def goto_current_match_link + open_url KDE::URL.new(@current_matched_href) unless @current_matched_href.nil? + end + + def skip_matches n + @current_matching_node_index += n # autowraps + if @in_node_highlight + @skipped_highlight_requests = true + return + end + update_highlight + end + + def goto_prev_match + skip_matches -1 + end + + def goto_next_match + skip_matches +1 + end + + def more_to_do + return false if @todo_links.empty? + lhref = @todo_links.pop + do_for_link lhref + true + end + + def do_for_link lhref + idx = (lhref.string =~ /#/) + unless idx.nil? + lhref = lhref.copy + lhref.truncate idx + end + skip = @done.include? lhref.string + return [] if skip +time_me("loading") { + @viewed.document.setAsync false + @viewed.document.load lhref +} + @done << lhref.string + newlinks = gather_for_current_page + @todo_next += newlinks + end + + def update_ui_elements + @forward.setEnabled !@popped_history.empty? + @back.setEnabled !@history.empty? + end + + def go_back + @popped_history << @url + fail "ummm... already at the start, gui bug" if @history.empty? + goto_url @history.pop, false, false + update_loc + update_ui_elements + end + + def go_forward + fail "history bug" if @popped_history.empty? + goto_url @popped_history.pop, false, false + @history << @url + update_loc + update_ui_elements + end + + def update_loc + # @location.setText @url.prettyURL + end + + def go_home + goto_url first_url + end + + def index_all + @viewed.hide + @id2uri.keys.each { + |id| goto_id_and_hl id + } + @viewed.show + end + + def goto_url url = nil, history_store = true, clear_forward = true + @popped_history = [] if clear_forward + if history_store + @history << @url + end + @url = KDE::URL.new(url.nil? ? @location.text : url) + @label.setText "Loading : #{@url.prettyURL}" + urlonly, = uri_anchor_split @url.url + id = @id2uri.invert[@url.url] + if id.nil? and !(should_follow? urlonly) + warn "link points outside indexed space!" + return + end + load_page + if id.nil? + gather_for_current_page + id = @shown_doc_id + index_current_document + else + @shown_doc_id = id + end + @label.setText "Ready" + update_loc unless url.nil? + update_ui_elements + end + +end + +m = KDE::MainWindow.new +browser = RubberDoc.new m +browser.update_ui_elements +guixmlfname = Dir.pwd + "/RubberDoc.rc" +guixmlfname = File.dirname(File.readlink $0) + "/RubberDoc.rc" unless File.exists? guixmlfname +m.createGUI guixmlfname +m.setCentralWidget browser +app.setMainWidget(m) +m.show +app.exec() +browser.finish + +__END__ + +TESTCASE - +w = KDE::HTMLPart # notice the missing .new +w.begin +=> crashes badly + +(RECHECK) +./kde.rb:29:in `method_missing': Cannot handle 'const QIconSet&' as argument to QTabWidget::changeTab (ArgumentError) + from ./kde.rb:29:in `initialize' + from ./kde.rb:92:in `new' + from ./kde.rb:92 +for param nil given to param const QIconSet & +occurs frequently + +dum di dum + +can't get tabwidget working. umm... wonder what i'm messing up... (RECHECK) + + tabwidget = KDE::TabWidget.new browser + tabwidget.setTabPosition Qt::TabWidget::Top + @viewed = KDE::HTMLPart.new tabwidget + w2 = KDE::HTMLPart.new tabwidget + tabwidget.changeTab @viewed, Qt::IconSet.new, "blah blah" + tabwidget.showPage @viewed + tabwidget.show + @viewed.show + +# possible BUG DOM::Text.new(node).data.string # strange that this one doesn't work... (RECHECK) + +wierd khtml bug + @rightpane.setResizeMode @viewed, Qt::Splitter::KeepSize + +in order to use KURL's as constants one must place this KApplication init +at the top of the file otherwise KInstance isn't init'ed before KURL usage + +class ProjectSelectDialog < KDE::DialogBase + def initialize parent=nil,name=nil,caption=nil + super(parent,name, true, caption, + KDE::DialogBase::Ok|KDE::DialogBase::Cancel, KDE::DialogBase::Ok, false, KDE::GuiItem.new) + blah blah + end +end + +# painter.fillRect 5, 5, width(listBox) - 10, height(listBox) - 10, Qt::Color.new(255,0,0) diff --git a/korundum/rubylib/examples/RubberDoc.rc b/korundum/rubylib/examples/RubberDoc.rc new file mode 100644 index 00000000..8e544b1a --- /dev/null +++ b/korundum/rubylib/examples/RubberDoc.rc @@ -0,0 +1,35 @@ +<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"> +<kpartgui name="xmlgui" version="2"> + +<MenuBar> + <Menu name="file" noMerge="1"><text>&File</text> + <Action name="index_all"/> + <Separator/> + <Action name="file_quit"/> + </Menu> +</MenuBar> + +<ToolBar name="projectToolbar" noMerge="1" fullWidth="true" iconText="icontextright"><text>Project Toolbar</text> + <Action name="project_create"/> + <Action name="project_delete"/> + <Action name="project_manage"/> + <Action name="project_goto"/> +</ToolBar> + +<ToolBar name="mainToolBar" noMerge="1" fullWidth="true" iconText="icontextright"><text>Main Toolbar</text> + <Action name="back"/> + <Action name="forward"/> + <Action name="home"/> + <Action name="prev_match"/> + <Action name="next_match"/> + <Action name="open_match"/> +</ToolBar> + +<ToolBar fullWidth="true" name="locationToolBar" newline="true"><text>Location Toolbar</text> + <Action name="clear_location" /> + <Action name="location_label" /> + <Action name="toolbar_url_combo" /> + <Action name="go_url" /> +</ToolBar> + +</kpartgui> diff --git a/korundum/rubylib/examples/dcop/dcopcall.rb b/korundum/rubylib/examples/dcop/dcopcall.rb new file mode 100755 index 00000000..f3b532ef --- /dev/null +++ b/korundum/rubylib/examples/dcop/dcopcall.rb @@ -0,0 +1,37 @@ +#!/usr/bin/env ruby + +require 'Korundum' +include KDE + +class SenderWidget < PushButton + def initialize(parent, name) + super + connect(self, SIGNAL('clicked()'), self, SLOT('doit()')) + end + + slots 'doit()' + + def doit() + dcopRef = DCOPRef.new("dcopslot", "MyWidget") + # + # Note that there are three different ways to make a DCOP call(): + # 1) result = dcopRef.call("getPoint(QString)", "Hello from dcopcall") + # 2) result = dcopRef.call("getPoint", "Hello from dcopcall") + # 3) result = dcopRef.getPoint("Hello from dcopcall") + # + result = dcopRef.getPoint("Hello from dcopcall") + if result.nil? + puts "DCOP call failed" + else + puts "result class: #{result.class.name} x: #{result.x} y: #{result.y}" + end + end +end + +about = AboutData.new("dcopcall", "DCOP Call Test", "0.1") +CmdLineArgs.init(ARGV, about) +a = UniqueApplication.new +calltest = SenderWidget.new(nil, "calltest") { setText 'DCOP Call Test' } +a.mainWidget = calltest +calltest.show +a.exec diff --git a/korundum/rubylib/examples/dcop/dcoppredicate.rb b/korundum/rubylib/examples/dcop/dcoppredicate.rb new file mode 100755 index 00000000..82a9c8b4 --- /dev/null +++ b/korundum/rubylib/examples/dcop/dcoppredicate.rb @@ -0,0 +1,41 @@ +#!/usr/bin/env ruby + +require 'Korundum' +include KDE + +class SenderWidget < PushButton + def initialize(parent, name) + super + connect(self, SIGNAL('clicked()'), self, SLOT('doit()')) + end + + slots 'doit()' + + def doit() + dcopRef = DCOPRef.new("dcopslot", "MyWidget") + # + # A synonym for isFoo() + result = dcopRef.foo? + if result.nil? + puts "DCOP predicate failed" + else + puts "foo? is #{result}" + end + + # A synonym for hasBar() + result = dcopRef.bar? + if result.nil? + puts "DCOP predicate failed" + else + puts "bar? is #{result}" + end + end +end + +about = AboutData.new("dcoppredicate", "DCOP Predicate Test", "0.1") +CmdLineArgs.init(ARGV, about) +a = UniqueApplication.new +calltest = SenderWidget.new(nil, "predicatetest") { setText 'DCOP Predicate Test' } +a.mainWidget = calltest +calltest.show +a.exec diff --git a/korundum/rubylib/examples/dcop/dcopsend.rb b/korundum/rubylib/examples/dcop/dcopsend.rb new file mode 100755 index 00000000..9365473b --- /dev/null +++ b/korundum/rubylib/examples/dcop/dcopsend.rb @@ -0,0 +1,35 @@ +#!/usr/bin/env ruby + +require 'Korundum' + +class SenderWidget < KDE::PushButton + def initialize(parent, name) + super + Qt::Object::connect(self, SIGNAL('clicked()'), self, SLOT('doit()')) + end + + slots 'doit()' + + def doit() + # + # Note that there are three different ways to make a DCOP send(): + # 1) dcopRef.send("mySlot(QString)", "Hello from dcopsend") + # 2) dcopRef.send("mySlot", "Hello from dcopsend") + # + dcopRef = KDE::DCOPRef.new("dcopslot", "MyWidget") + res = dcopRef.send("mySlot", "Hello from dcopsend") + if res + puts "Sent dcop message" + else + puts "DCOP send failed" + end + end +end + +about = KDE::AboutData.new("dcopsend", "DCOPSendTest", "0.1") +KDE::CmdLineArgs.init(ARGV, about) +a = KDE::Application.new() +sender = SenderWidget.new(nil, "senderwidget") { setText 'DCOP Send Test' } +a.setMainWidget(sender) +sender.show() +a.exec() diff --git a/korundum/rubylib/examples/dcop/dcopsignal.rb b/korundum/rubylib/examples/dcop/dcopsignal.rb new file mode 100755 index 00000000..07a6dfee --- /dev/null +++ b/korundum/rubylib/examples/dcop/dcopsignal.rb @@ -0,0 +1,26 @@ +#!/usr/bin/env ruby + +require 'Korundum' + +class SenderWidget < KDE::PushButton + k_dcop_signals 'void testEmitSignal(QString)' + + def initialize(parent, name) + super + Qt::Object::connect(self, SIGNAL('clicked()'), self, SLOT('doit()')) + end + + slots 'doit()' + + def doit() + emit testEmitSignal("Hello DCOP Slot") + end +end + +about = KDE::AboutData.new("dcopsignal", "DCOPSignalTest", "0.1") +KDE::CmdLineArgs.init(ARGV, about) +a = KDE::UniqueApplication.new() +signaltest = SenderWidget.new(nil, "foobar") { setText 'DCOP Signal Test' } +a.mainWidget = signaltest +signaltest.show() +a.exec() diff --git a/korundum/rubylib/examples/dcop/dcopslot.rb b/korundum/rubylib/examples/dcop/dcopslot.rb new file mode 100755 index 00000000..e600dfdb --- /dev/null +++ b/korundum/rubylib/examples/dcop/dcopslot.rb @@ -0,0 +1,88 @@ +#!/usr/bin/env ruby + +require 'Korundum' + +# This is an example of a KDE class that has 'k_dcop' slots declarations, but +# isn't a subclass of DCOPObject. The following four methods are added to your +# class: +# +# interfaces() +# functions() +# connectDCOPSignal() +# disconnectDCOPSignal() +# +# See the call to connectDCOPSignal() towards the end of the code as +# an example. The name of the dcop object is always the name of the +# ruby class, and they are Singletons - you can only instantiate one +# of them. +# +# The petshop.rb example in this directory demonstrates more complex +# use of korundum dcop by subclassing a DCOPObject. +# +class MyWidget < KDE::PushButton + + k_dcop 'void mySlot(QString)', + 'QPoint getPoint(QString)', + 'QMap<QCString,DCOPRef> actionMap()', + 'QValueList<DCOPRef> windowList()', + 'QValueList<QCString> propertyNames(bool)', + 'KURL::List urlList()', + 'bool isFoo()', + 'bool hasBar()' + + def initialize(parent, name) + super + end + + def mySlot(greeting) + puts "greeting: #{greeting}" + end + + def getPoint(msg) + puts "message: #{msg}" + return Qt::Point.new(50, 100) + end + + def actionMap() + map = {} + map['foobar'] = KDE::DCOPRef.new("myapp", "myobj") + return map + end + + def windowList() + list = [] + list[0] = KDE::DCOPRef.new("myapp", "myobj") + return list + end + + def propertyNames(b) + return ["thisProperty", "thatProperty"] + end + + def urlList() + list = [] + list << KDE::URL.new("http://www.kde.org/") << KDE::URL.new("http://dot.kde.org/") + return list + end + + def isFoo + true + end + + def hasBar + true + end +end + +about = KDE::AboutData.new("dcopslot", "dcopSlotTest", "0.1") +KDE::CmdLineArgs.init(ARGV, about) +a = KDE::UniqueApplication.new() +slottest = MyWidget.new(nil, "mywidget") { setText "DCOP Slot Test" } +a.mainWidget = slottest +slottest.caption = a.makeStdCaption("DCOP Slot Test") +result = slottest.connectDCOPSignal("dcopsignal", "SenderWidget", "testEmitSignal(QString)", "mySlot(QString)", true) +puts "result: #{result}" + +slottest.show() +# Qt::Internal::setDebug Qt::QtDebugChannel::QTDB_ALL +a.exec() diff --git a/korundum/rubylib/examples/dcop/dcoptest.rb b/korundum/rubylib/examples/dcop/dcoptest.rb new file mode 100755 index 00000000..7d42f76e --- /dev/null +++ b/korundum/rubylib/examples/dcop/dcoptest.rb @@ -0,0 +1,129 @@ +#!/usr/bin/env ruby +=begin +This is a ruby version of Jim Bublitz's pykde program, translated by Richard Dale +=end + +=begin +Copyright 2003 Jim Bublitz + +Terms and Conditions + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +Except as contained in this notice, the name of the copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in this Software without prior written authorization from the +copyright holder. +=end + + +require 'Korundum' + +module DCOPTest + + def DCOPTest.getAnyApplication(client, appName) + client.registeredApplications().each do |app| + if app == appName or app =~ Regexp.new("^#{appName}-") + puts app + puts + objList = client.remoteObjects(app) + objList.each do |obj| + puts " #{obj}" + funcs = client.remoteFunctions(app, obj) + funcs.each { |f| puts " #{f}" } + end + end + end + end + +end + +#-------------------- main ------------------------------------------------ + +description = "A basic application template" +version = "1.0" +aboutData = KDE::AboutData.new("testdcopext", "testdcopext", + version, description, KDE::AboutData::License_GPL, + "(C) 2003 whoever the author is") + +aboutData.addAuthor("author1", "whatever they did", "email@somedomain") +aboutData.addAuthor("author2", "they did something else", "another@email.address") + +KDE::CmdLineArgs.init(ARGV, aboutData) + +KDE::CmdLineArgs.addCmdLineOptions([["+files", "File to open", ""]]) + +app = KDE::Application.new +dcop = app.dcopClient +puts "DCOP Application: #{dcop.appId} starting" + +# DCOPTest.getAnyApplication(dcop, "konqueror") + +puts "--------------------------" +puts "The DCOPObjects for kicker:" + +d = KDE::DCOPRef.new('kicker') +objs = d.interfaces() +objs.each { |obj| puts obj } + +puts +puts "get kicker panel size via DCOP" +res = d.panelSize() +puts res +puts "--------------------------" + +puts +puts "Call a method that doesn't exist" +res = d.junk() +puts (res.nil? ? "Call failed" : "Call succeeded") +puts "--------------------------" + +puts +puts +puts "Start a kwrite instance" + +error = "" +dcopService = "" +pid = Qt::Integer.new + +errcode = KDE::Application.startServiceByDesktopName("kwrite", "", error, dcopService, pid) +dcopService = "kwrite-" + pid.to_s +puts "errcode: #{errcode.to_s} error: #{error} dcopService: #{dcopService} pid: #{pid.to_s}" +puts "--------------------------" +sleep(2) + +o1 = KDE::DCOPRef.new(dcopService, "EditInterface#1") +#puts "Check if insertLine is a valid function" +#puts "valid", o1.insertLine.valid +#puts "--------------------------" +#puts "insertLine's arg types and names" +# puts o1.insertLine.argtypes, o1.insertLine.argnames +puts "--------------------------" +puts "Insert a line into the kwrite instance we launched" + +res = o1.insertLine(0, 'Now is the time for all good men to come to the aid of their party') +if res.nil? + puts "call returns: failed" +else + puts "call returns: #{res.to_s}" +end + +app.exec + + diff --git a/korundum/rubylib/examples/dcop/petshop.rb b/korundum/rubylib/examples/dcop/petshop.rb new file mode 100755 index 00000000..0cce6277 --- /dev/null +++ b/korundum/rubylib/examples/dcop/petshop.rb @@ -0,0 +1,91 @@ +#!/usr/bin/env ruby + +# This is an example of a DCOP enabled application written in Ruby, using +# Korundum. Taken from the PyKDE example_dcopexport.py example which was +# derived from server.py example in kdebindings written by Torben Weis +# and Julian Rockey + +require 'Korundum' + +# An object with DCOP slots needn't be a subclass of DCOPObject, but +# this DeadParrotObject is one + +class DeadParrotObject < KDE::DCOPObject + + k_dcop 'QString getParrotType()', 'void setParrotType(QString)', + 'QString squawk()', 'QStringList adjectives()', + 'int age()', 'void setAge(int)' + + def initialize(id = 'dead parrot') + super(id) + @parrot_type = "Norwegian Blue" + @age = 7 + end + + def getParrotType() + @parrot_type + end + + def setParrotType(parrot_type) + @parrot_type = parrot_type + end + + def age() + @age + end + + def setAge(a) + @age = a + end + + def squawk + if rand(2) == 0 + "This parrot, a #{@parrot_type}, is pining for the fjords" + else + "This parrot, #{@age} months old, is a #{@parrot_type}" + end + end + + def adjectives + return ["passed on", "is no more", "ceased to be", "expired", "gone to meet his maker", + "a stiff", "bereft of life", "rests in peace", "metabolic processes are now history", + "off the twig", "kicked the bucket", "shuffled off his mortal coil", + "run down his curtain", "joined the bleedin' choir invisible", "THIS IS AN EX-PARROT"] + end +end + +description = "A basic application template" +version = "1.0" +aboutData = KDE::AboutData.new("petshop", "Dead Parrot Test", + version, description, KDE::AboutData::License_GPL, + "(C) 2003 whoever the author is") + +aboutData.addAuthor("author1", "whatever they did", "email@somedomain") +aboutData.addAuthor("author2", "they did something else", "another@email.address") + +KDE::CmdLineArgs.init(ARGV, aboutData) + +KDE::CmdLineArgs.addCmdLineOptions([["+files", "File to open", ""]]) + +app = KDE::UniqueApplication.new +dcop = app.dcopClient +puts "DCOP Application: #{dcop.appId} starting" + +parrot = DeadParrotObject.new +another_parrot = DeadParrotObject.new('polly') + +message = <<EOS +Run kdcop and look for the 'petshop' application instance. + +This program exports the DeadParrotObject object. +Double-clicking those object's methods will allow you to get or set data. + +To end the application, in kdcop choose the MainApplication-Interface +object and double-click the quit() method. +EOS + +print message + +app.exec + + diff --git a/korundum/rubylib/examples/kludgeror.rb b/korundum/rubylib/examples/kludgeror.rb new file mode 100644 index 00000000..535936b2 --- /dev/null +++ b/korundum/rubylib/examples/kludgeror.rb @@ -0,0 +1,138 @@ +#!/usr/bin/env ruby +# A quick and dirty web browser demonstrating the direct instantiation +# of a KHTML part. Needless to say: this is NOT a programming paragon :) +# -- gg. +# AK - ported to ruby + +require 'Korundum' + +opt = [ [ "+[url]", "An URL to open at startup.", "" ], + [ "z", "A dummy binary option.", "" ], + [ "baz <file>", "A long option with arg.", "" ], + [ "boz <file>", "Same as above with default value", "default.txt" ], + ] + +#Qt::Internal::setDebug Qt::QtDebugChannel::QTDB_ALL +# Qt.debug_level = Qt::DebugLevel::High + +about = KDE::AboutData.new("kludgeror", "Kludgeror", "0.1", "A basic web browser") +KDE::CmdLineArgs::init(ARGV, about) +KDE::CmdLineArgs::addCmdLineOptions opt +args = KDE::CmdLineArgs::parsedArgs + +a = KDE::Application.new # BUG, application shouldn't be needed at the top, lets fix this... + +class PartHolder < Qt::Object + signals "setLocBarText(const QString&)" + slots "reload()", "goToURL(const QString&)", "back()", "openURL(const KURL&)" # BUG - the slots should be normalize wrt spaces by the lib + + attr_accessor :part, :history + + def initialize part, *k + super(*k) + @part = part + @history = [] + end + + def openURL url + @part.openURL url + # BUG - a non existant slot emit says horrible things, nothing interesting for user.. very confusing + # BUG - signal emitting is *very* wrong + # emit setLocBarText(url.url) + @history.unshift url unless url == @history[0] + end + + def reload + @part.openURL @part.url + end + + def goToURL(url) + url = "http://#{url}" unless url =~ /^\w*:/ + openURL KDE::URL.new(url) + end + + def back + return unless @history.length > 1 + @history.shift + openURL @history[0] unless @history.empty? + end +end + +LOC_ED = 322 +ERASE_B = 323 +BACK_B = 324 + +url = (args.count > 1) ? args.url(0) : KDE::URL.new("http://loki:8080/xml/index.xml") + +puts "Dummy z option activated." if args.isSet "z" +puts "Dummy baz option has value: #{args.getOption "baz"}" if args.isSet "baz" +# puts "Dummy boz option has value: #{args.getOption "boz"}" if args.isSet "boz" # B0rked? + +toplevel = KDE::MainWindow.new +doc = KDE::HTMLPart.new toplevel, nil, toplevel, nil, 1 +# doc = KDE::HTMLPart.new toplevel, nil, toplevel, nil, 1 # KDE::HTMLPart::BrowserViewGUI +ph = PartHolder.new doc + +Qt::Object::connect doc.browserExtension, SIGNAL("openURLRequest(const KURL&, const KParts::URLArgs&)"), + ph, SLOT("openURL(const KURL&)") # BUG this slot must be screwing up wrt marshalling? + +ph.openURL url +toplevel.setCentralWidget doc.widget +toplevel.resize 700, 500 + +begin + d, viewMenu, fileMenu, locBar, e = nil + d = doc.domDocument + viewMenu = d.documentElement.firstChild.childNodes.item(2).toElement + e = d.createElement "action" + e.setAttribute "name", "debugRenderTree" + viewMenu.appendChild e + e = d.createElement "action" + e.setAttribute "name", "debugDOMTree" + viewMenu.appendChild e + fileMenu = d.documentElement.firstChild.firstChild.toElement + fileMenu.appendChild d.createElement("separator") + e = d.createElement "action" + e.setAttribute "name", "exit" + fileMenu.appendChild e + locBar = d.createElement "toolbar" + locBar.setAttribute "name", "locationBar" + e = d.createElement "action" + e.setAttribute "name", "reload" + locBar.appendChild e + d.documentElement.appendChild locBar +end + +a1 = KDE::Action.new( "Reload", "reload", KDE::Shortcut.new(Qt::Key_F5), ph, SLOT("reload()"), doc.actionCollection, "reload" ) +a2 = KDE::Action.new( "Exit", "exit", KDE::Shortcut.new(0), a, SLOT("quit()"), doc.actionCollection, "exit" ) + +toplevel.guiFactory.addClient doc + +locBar = toplevel.toolBar("locationBar"); +locBar.insertButton "back", BACK_B, SIGNAL("clicked()"), + ph, SLOT("back()"), true, "Go back" +locBar.insertLined url.url, LOC_ED, SIGNAL("returnPressed(const QString&)"), ph, SLOT("goToURL(const QString&)"), true, "Location" +locBar.insertButton "locationbar_erase", ERASE_B, SIGNAL("clicked()"), + locBar.getLined(LOC_ED), SLOT("clear()"), true, "Erase the location bar's content", 2 +locBar.setItemAutoSized LOC_ED, true +locBar.getLined(LOC_ED).createPopupMenu +comp = locBar.getLined(LOC_ED).completionObject +comp.setCompletionMode KDE::GlobalSettings::CompletionPopupAuto + +Qt::Object::connect(locBar.getLined(LOC_ED), SIGNAL("returnPressed(const QString&)"), + comp, SLOT("addItem(const QString&)")) +Qt::Object::connect(ph, SIGNAL("setLocBarText(const QString&)"), # BUG - once again... + locBar.getLined(LOC_ED), SLOT("setText(const QString&)")) + +doc.setJScriptEnabled true +doc.setJavaEnabled true +doc.setPluginsEnabled true +doc.setURLCursor Qt::Cursor.new(Qt::PointingHandCursor) + +a.setTopWidget doc.widget + +Qt::Object::connect doc, SIGNAL("setWindowCaption(const QString&)"), + doc.widget.topLevelWidget, SLOT("setCaption(const QString&)") +toplevel.show + +a.exec diff --git a/korundum/rubylib/examples/kurldemo.rb b/korundum/rubylib/examples/kurldemo.rb new file mode 100644 index 00000000..04fb9bce --- /dev/null +++ b/korundum/rubylib/examples/kurldemo.rb @@ -0,0 +1,110 @@ +=begin +This is a ruby version of Jim Bublitz's pykde program, translated by Richard Dale +=end + +=begin +Copyright 2003 Jim Bublitz + +Terms and Conditions + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +Except as contained in this notice, the name of the copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in this Software without prior written authorization from the +copyright holder. +=end + +require 'Korundum' + +class MainWin < KDE::MainWindow + def initialize(*args) + super + + @urls = ["http://slashdot.org", "http://www.kde.org", "http://www.riverbankcomputing.co.uk", "http://yahoo.com"] + setGeometry(0, 0, 400, 600) + + edit = KDE::TextEdit.new(self) + setCentralWidget(edit) + + edit.insert("KURL Demo\n") + edit.insert("\nAdding these urls:\n\n") + @urls.each do |url| + edit.insert(" #{url}\n") + end + + edit.insert("\nCreating KURLs (iterating to print):\n\n") + urlList = [] + @urls.each do |url| + urlList << KDE::URL.new(url) + end + + urlList.each do |url| + edit.insert(" #{url.url()}\n") + end + + edit.insert("\nFirst url -- urlList [0]:\n\n") + edit.insert(" #{urlList[0].to_s}\n") + edit.insert(" #{urlList[0].url()}\n") + + edit.insert("\nLast url -- urlList [-1]:\n\n") + edit.insert(" #{urlList[-1].to_s}\n") + edit.insert(" #{urlList[-1].url()}\n") + + edit.insert("\nMiddle urls -- urlList [2,4]:\n\n") + ulist = urlList[2,4] + ulist.each do |url| + edit.insert(" #{url.to_s}\n") + edit.insert(" #{url.url()}\n") + end + + edit.insert("\nLength of urlList -- len (urlList):\n\n") + edit.insert(" Length = #{urlList.length}\n") + + edit.insert("\nurl in urlList? -- KURL (\"http://yahoo.com\") in urlList\n\n") + edit.insert(" KDE::URL.new(\"http://yahoo.com\") in urlList = ") + tmp = KDE::URL.new("http://yahoo.com") + urlList.each do |url| + if url.url == tmp.url + edit.insert("true") + end + end + end +end + + +#-------------------- main ------------------------------------------------ + +description = "A basic application template" +version = "1.0" +aboutData = KDE::AboutData.new("", "", + version, description, KDE::AboutData::License_GPL, + "(C) 2003 whoever the author is") + +aboutData.addAuthor("author1", "whatever they did", "email@somedomain") +aboutData.addAuthor("author2", "they did something else", "another@email.address") + +KDE::CmdLineArgs.init(ARGV, aboutData) + +KDE::CmdLineArgs.addCmdLineOptions([["+files", "File to open", ""]]) + +app = KDE::Application.new() +mainWindow = MainWin.new(nil, "main window") +mainWindow.show() +app.exec() diff --git a/korundum/rubylib/examples/menudemo.rb b/korundum/rubylib/examples/menudemo.rb new file mode 100644 index 00000000..d5762ecd --- /dev/null +++ b/korundum/rubylib/examples/menudemo.rb @@ -0,0 +1,310 @@ +=begin +This is a ruby version of Jim Bublitz's pykde program, translated by Richard Dale +=end + +=begin +This template constructs an application with menus, toolbar and statusbar. +It uses KDE classes and methods that simplify the task of building and +operating a GUI. It is recommended that this approach be used, rather +than the primitive approach in menuapp1.py +=end + +=begin +Copyright 2003 Jim Bublitz + +Terms and Conditions + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +Except as contained in this notice, the name of the copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in this Software without prior written authorization from the +copyright holder. +=end + +require 'Korundum' +include KDE + +class MainWin < MainWindow + + slots 'slotNew()', 'slotOpen()', 'slotSave()', 'slotSaveAs()', 'slotPrint()', 'slotQuit()', 'slotUndo()', + 'slotRedo()', 'slotCut()', 'slotCopy()', 'slotPaste()', 'slotFind()', 'slotFindNext()', 'slotReplace()', + 'slotSpecial()', 'slotToggle2()', 'slotZoomIn()', 'slotZoomOut()' + + STATUSBAR_LEFT = 1 + STATUSBAR_MIDDLE = 2 + STATUSBAR_RIGHT = 3 + + def initialize(*args) + super + + initActions() + initMenus() + initToolBar() + initStatusBar() + + @saveAction.setEnabled(false) + @saveAsAction.setEnabled(false) + end + + def initActions() + # "File" menu items + @newAction = StdAction.openNew(self, SLOT('slotNew()'), actionCollection()) + @openAction = StdAction.open(self, SLOT('slotOpen()'), actionCollection()) + @saveAction = StdAction.save(self, SLOT('slotSave()'), actionCollection()) + @saveAsAction = StdAction.saveAs(self, SLOT('slotSaveAs()'), actionCollection()) + @printAction = StdAction.print(self, SLOT('slotPrint()'), actionCollection()) + @quitAction = StdAction.quit(self, SLOT('slotQuit()'), actionCollection()) + + # "Edit" menu items + @undoAction = StdAction.undo(self, SLOT('slotUndo()'), actionCollection()) + @redoAction = StdAction.redo(self, SLOT('slotRedo()'), actionCollection()) + @cutAction = StdAction.cut(self, SLOT('slotCut()'), actionCollection()) + @copyAction = StdAction.copy(self, SLOT('slotCopy()'), actionCollection()) + @pasteAction = StdAction.paste(self, SLOT('slotPaste()'), actionCollection()) + @findAction = StdAction.find(self, SLOT('slotFind()'), actionCollection()) + @findNextAction = StdAction.findNext(self, SLOT('slotFindNext()'), actionCollection()) + @replaceAction = StdAction.replace(self, SLOT('slotReplace()'), actionCollection()) + @specialAction = Action.new(i18n("Special"), Shortcut.new(), self, SLOT('slotSpecial()'), actionCollection(), "special") + + # Demo menu items + + # KToggleAction has an isChecked member and emits the "toggle" signal + @toggle1Action = ToggleAction.new("Toggle 1") + @toggle2Action = ToggleAction.new("Toggle 2", Shortcut.new(), self, SLOT('slotToggle2()'), nil) + + # A separator - create once/use everywhere + @separateAction = ActionSeparator.new() + + # Font stuff in menus or toolbar + @fontAction = FontAction.new("Font") + @fontSizeAction = FontSizeAction.new("Font Size") + + # Need to assign an icon to actionMenu below + icons = IconLoader.new() + iconSet = Qt::IconSet.new(icons.loadIcon("viewmag", Icon::Toolbar)) + + # Nested menus using KActions (also nested on toolbar) + @actionMenu = ActionMenu.new("Action Menu") + @actionMenu.setIconSet(iconSet) + @actionMenu.insert(StdAction.zoomIn(self, SLOT('slotZoomIn()'), actionCollection())) + @actionMenu.insert(StdAction.zoomOut(self, SLOT('slotZoomOut()'), actionCollection())) + + # Doesn't work in KDE 2.1.1 +# radio1Action = KRadioAction ("Radio 1") +# radio1Action.setExclusiveGroup ("Radio") +# radio2Action = KRadioAction ("Radio 2") +# radio2Action.setExclusiveGroup ("Radio") +# radio3Action = KRadioAction ("Radio 3") +# radio3Action.setExclusiveGroup ("Radio") + end + + def initMenus() + fileMenu = Qt::PopupMenu.new(self) + @newAction.plug(fileMenu) + @openAction.plug(fileMenu) + fileMenu.insertSeparator() + @saveAction.plug(fileMenu) + @saveAsAction.plug(fileMenu) + fileMenu.insertSeparator() + @printAction.plug(fileMenu) + fileMenu.insertSeparator() + @quitAction.plug(fileMenu) + menuBar().insertItem(i18n("&File"), fileMenu) + + editMenu = Qt::PopupMenu.new(self) + @undoAction.plug(editMenu) + @redoAction.plug(editMenu) + editMenu.insertSeparator() + @cutAction.plug(editMenu) + @copyAction.plug(editMenu) + @pasteAction.plug(editMenu) + editMenu.insertSeparator() + @findAction.plug(editMenu) + @findNextAction.plug(editMenu) + @replaceAction.plug(editMenu) + editMenu.insertSeparator() + @specialAction.plug(editMenu) + menuBar().insertItem(i18n("&Edit"), editMenu) + + demoMenu = Qt::PopupMenu.new(self) + @toggle1Action.plug(demoMenu) + @toggle2Action.plug(demoMenu) + @separateAction.plug(demoMenu) + @fontAction.plug(demoMenu) + @fontSizeAction.plug(demoMenu) + @actionMenu.plug(demoMenu) +# radio1Action.plug(demoMenu) +# radio2Action.plug(demoMenu) +# radio3Action.plug(demoMenu) + menuBar().insertItem(i18n("&Demo"), demoMenu) + + # This really belongs in Kicker, not here, + # but it actually works + # wlMenu = WindowListMenu.new(self) + # wlMenu.init() + # menuBar().insertItem(i18n("&WindowListMenu"), wlMenu) + + helpMenu = helpMenu("") + menuBar().insertItem(i18n("&Help"), helpMenu) + end + + def initToolBar() + @newAction.plug(toolBar()) + @openAction.plug(toolBar()) + @saveAction.plug(toolBar()) + @cutAction.plug(toolBar()) + @copyAction.plug(toolBar()) + @pasteAction.plug(toolBar()) + + @separateAction.plug(toolBar()) + @separateAction.plug(toolBar()) + @separateAction.plug(toolBar()) + + @fontAction.plug(toolBar()) + @separateAction.plug(toolBar()) + @fontAction.setComboWidth(150) + + @fontSizeAction.plug(toolBar()) + @fontSizeAction.setComboWidth(75) + + @separateAction.plug(toolBar()) + + # This works, but you have to hold down the + # button in the toolbar and wait a bit + @actionMenu.plug(toolBar()) + # This appears to do nothing + @actionMenu.setDelayed(false) + + # Need this to keep the font comboboxes from stretching + # to the full width of the toolbar when the window is + # maximized (comment out the next two lines to see + # what happens) + stretchlbl = Qt::Label.new("", toolBar()) + toolBar().setStretchableWidget(stretchlbl) + +# toolBar().setHorizontalStretchable(false) + end + + def initStatusBar() + statusBar().insertItem("", STATUSBAR_LEFT, 1000, true) + statusBar().insertItem("", STATUSBAR_MIDDLE, 1000, true) + statusBar().insertItem("", STATUSBAR_RIGHT, 1000, true) + end + +#-------------------- slots ----------------------------------------------- + + def slotNew(id = -1) + notImpl("New") + end + + def slotOpen(id = -1) + notImpl("Open") + end + + def slotSave(id = -1) + notImpl("Save") + end + + def slotSaveAs() + notImpl("Save As") + end + + def slotPrint() + notImpl("Print") + end + + def slotQuit() + notImpl("Quit") + end + + def slotUndo() + notImpl("Undo") + end + + def slotRedo() + notImpl("Redo") + end + + def slotCut (id = -1) + notImpl("Cut") + end + + def slotCopy(id = -1) + notImpl("Copy") + end + + def slotPaste(id = -1) + notImpl("Paste") + end + + def slotFind() + notImpl("Find") + end + + def slotFindNext() + notImpl("Find Next") + end + + def slotReplace() + notImpl("Replace") + end + + def slotSpecial() + notImpl("Special") + end + + def slotToggle2() + notImpl("Toggle") + end + + def slotZoomIn() + notImpl("Zoom In") + end + + def slotZoomOut() + notImpl("Zoom Out") + end + + def notImpl(item) + statusBar().changeItem("#{item} not implemented", STATUSBAR_LEFT) + MessageBox.error(self, "#{item} not implemented", "Not Implemented") + statusBar().changeItem("", STATUSBAR_LEFT) + end +end + +#-------------------- main ------------------------------------------------ + +description = "A basic application template" +version = "1.0" +aboutData = AboutData.new("menudemo", "MenuDemo", + version, description, AboutData::License_GPL, + "(C) 2003 whoever the author is") + +aboutData.addAuthor("author1", "whatever they did", "email@somedomain") +aboutData.addAuthor("author2", "they did something else", "another@email.address") + +CmdLineArgs.init(ARGV, aboutData) + +CmdLineArgs.addCmdLineOptions([["+files", "File to open", ""]]) + +app = Application.new() +mainWindow = MainWin.new(nil, "main window") +mainWindow.show() +app.exec() diff --git a/korundum/rubylib/examples/mimetype.rb b/korundum/rubylib/examples/mimetype.rb new file mode 100644 index 00000000..9f6db85f --- /dev/null +++ b/korundum/rubylib/examples/mimetype.rb @@ -0,0 +1,286 @@ +=begin +This is a ruby version of Jim Bublitz's pykde program, translated by Richard Dale +=end + +=begin +This program tests/demos some of the KSharedPtr related classes and +methods (KMimeType, KService, etc). It generally tests the *::List +methods for these classes (eg KService::List) since that also tests +the *::Ptr mapped type code (eg KService::Ptr) at the same time. + +This version is suitable for KDE >= 3.0.0 (some methods not available +in earlier versions) +=end + +=begin +Copyright 2003 Jim Bublitz + +Terms and Conditions + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +Except as contained in this notice, the name of the copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in this Software without prior written authorization from the +copyright holder. +=end + +require 'Korundum' +include KDE + +class MainWin < MainWindow + def initialize(*k) + super + + tabctl = KDE::TabCtl.new(self) + setGeometry(0, 0, 600, 400) + tabctl.setGeometry(10, 10, 550, 380) + + tabctl.addTab(KMimeTypeTab.new(tabctl), "KMimeType") + tabctl.addTab(KServiceTab.new(tabctl), "KService") + tabctl.addTab(KSycocaEntryTab.new(tabctl), "KSycocaEntry") + tabctl.addTab(KServiceTypeTab.new(tabctl), "KServiceType") + tabctl.addTab(OfferListTab.new(tabctl), "OfferList") + + tabctl.show() + end +end + + +class OfferListTab < Qt::Widget + def initialize(parent, name = "") + super(parent, name) + + setGeometry(0, 0, 500, 370) + lvLbl = Qt::Label.new("Offers - text/html", self) + lvLbl.setGeometry(10, 10, 150, 20) + + lv = Qt::ListView.new(self) + lv.setSorting(-1) + lv.addColumn("type", 75) + lv.addColumn("name", 100) + lv.addColumn("exec", 200) + lv.addColumn("library", 100) + lv.setGeometry(10, 30, 500, 300) + lv.setAllColumnsShowFocus(true) + + # insert list items in reverse order + + pref = KDE::ServiceTypeProfile.preferredService("Application", "image/jpeg") + Qt::ListViewItem.new(lv, pref.type(), pref.name(), pref.exec(), pref.library()) + Qt::ListViewItem.new(lv, "Preferred", "--------", "", "") + Qt::ListViewItem.new(lv, "", "", "", "") + + trader = KDE::Trader.self() + slist = trader.query("image/jpeg", "Type == 'Application'") +# print "KTrader returned:" + slist + slist.each do |s| + lvi = Qt::ListViewItem.new(lv, s.type(), s.name(), s.exec(), s.library()) + end + + lv.show() + end +end + +class KServiceTypeTab < Qt::Widget + def initialize(parent, name = "") + super(parent, name) + + setGeometry(0, 0, 500, 370) + lvLbl = Qt::Label.new("All Service Types", self) + lvLbl.setGeometry(10, 10, 250, 20) + + lv = Qt::ListView.new(self) + lv.addColumn("name", 150) + lv.addColumn("desktopEntryPath", 300) + lv.setGeometry(10, 30, 500, 300) + lv.setAllColumnsShowFocus(true) + + slist = KDE::ServiceType.allServiceTypes() + + slist.each do |s| + lvi = Qt::ListViewItem.new(lv, s.name(), s.desktopEntryPath()) + end + + lv.show() + end +end + +class KSycocaEntryTab < Qt::Widget + def initialize(parent, name = "") + super(parent, name) + + grp = KDE::ServiceGroup.baseGroup("screensavers") + if grp.nil? + return + end + setGeometry(0, 0, 500, 370) + lvLbl = Qt::Label.new("Entries - 'screensavers': " + grp.name(), self) + lvLbl.setGeometry(10, 10, 250, 20) + + lv = Qt::ListView.new(self) + lv.addColumn("name", 150) + lv.addColumn("entryPath", 300) + lv.setGeometry(10, 30, 500, 300) + lv.setAllColumnsShowFocus(true) + + slist = grp.entries(false, false) + + slist.each do |s| + lvi = Qt::ListViewItem.new(lv, s.name(), s.entryPath()) + end + + lv.show() + end +end + +class KServiceTab < Qt::Widget + def initialize(parent, name = "") + super(parent, name) + + setGeometry(0, 0, 500, 370) + lvLbl = Qt::Label.new("All Services", self) + lvLbl.setGeometry(10, 10, 150, 20) + + lv = Qt::ListView.new(self) + lv.addColumn("type", 75) + lv.addColumn("name", 100) + lv.addColumn("exec", 200) + lv.addColumn("library", 100) + lv.setGeometry(10, 30, 500, 300) + lv.setAllColumnsShowFocus(true) + + slist = KDE::Service.allServices() + slist.each do |s| + lvi = Qt::ListViewItem.new(lv, s.type(), s.name(), s.exec(), s.library()) + end + + lv.show() + end +end + +# svc = KService.serviceByDesktopName ("kcookiejar") +# print svc +# print svc.type_ () +# print svc.name ().latin1 () +# print svc.exec_ ().latin1 () +# print svc.library () + + +class KMimeTypeTab < Qt::Widget + def initialize(parent, name = "") + super(parent, name) + + setGeometry(0, 0, 500, 370) + lbLbl = Qt::Label.new("All Mimetypes", self) + lbLbl.setGeometry(10, 10, 150, 20) + lb = KDE::ListBox.new(self) + lb.setGeometry(10, 30, 200, 300) + mlist = KDE::MimeType.allMimeTypes() + lblist = [] + mlist.each do |mt| + lblist << mt.name() + end + + lblist.sort() + lb.insertStringList(lblist) + + lb.show() + + x = 250 + y = 10 + + mt = KDE::MimeType.mimeType("text/plain") + mtlbl = Qt::Label.new("KMimeType.mimeType('text/plain')", self) + mtlbl.setGeometry(x, y, 250, 20) + mtnamelbl = Qt::Label.new("name", self) + mtnamelbl.setGeometry(x + 15, y + 20, 100, 20) + mtname = Qt::Label.new(mt.name(), self) + mtname.setGeometry(x + 120, y + 20, 100, 20) + mtdesklbl = Qt::Label.new("desktopEntryPath", self) + mtdesklbl.setGeometry(x + 15, y + 40, 100, 20) + mtdesk = Qt::Label.new(mt.desktopEntryPath(), self) + mtdesk.setGeometry(x + 120, y + 40, 150, 20) + + y = y + 80 + + fp = KDE::MimeType.findByPath("mimetype.rb") + fplbl = Qt::Label.new("KDE::MimeType.findByPath('mimetype.rb')", self) + fplbl.setGeometry(x, y, 250, 20) + fpnamelbl = Qt::Label.new("name", self) + fpnamelbl.setGeometry(x + 15, y + 20, 100, 20) + fpname = Qt::Label.new(fp.name(), self) + fpname.setGeometry(x + 120, y + 20, 100, 20) + fpdesklbl = Qt::Label.new("desktopEntryPath", self) + fpdesklbl.setGeometry(x + 15, y + 40, 100, 20) + fpdesk = Qt::Label.new(fp.desktopEntryPath(), self) + fpdesk.setGeometry(x + 120, y + 40, 150, 20) + + y = y + 80 + + fu = KDE::MimeType.findByURL(KDE::URL.new("file://mimetype.rb")) + fulbl = Qt::Label.new("KDE::MimeType.findByURL('file://mimetype.rb')", self) + fulbl.setGeometry(x, y, 250, 20) + funamelbl = Qt::Label.new("name", self) + funamelbl.setGeometry(x + 15, y + 20, 100, 20) + funame = Qt::Label.new(fu.name(), self) + funame.setGeometry(x + 120, y + 20, 100, 20) + fudesklbl = Qt::Label.new("desktopEntryPath", self) + fudesklbl.setGeometry(x + 15, y + 40, 100, 20) + fudesk = Qt::Label.new(fu.desktopEntryPath(), self) + fudesk.setGeometry(x + 120, y + 40, 150, 20) + + y = y + 80 + + acc = Qt::Integer.new(0) # Create a mutable integer value to pass as an 'int*' arg + fc = KDE::MimeType.findByFileContent("mimetype.rb", acc) + fclbl = Qt::Label.new("KDE::MimeType.findByFileContent('mimetype.rb')", self) + fclbl.setGeometry(x, y, 250, 20) + fcnamelbl = Qt::Label.new("name", self) + fcnamelbl.setGeometry(x + 15, y + 20, 100, 20) + fcname = Qt::Label.new(fc.name(), self) + fcname.setGeometry(x + 120, y + 20, 100, 20) + fcdesklbl = Qt::Label.new("desktopEntryPath", self) + fcdesklbl.setGeometry(x + 15, y + 40, 100, 20) + fcdesk = Qt::Label.new(fc.desktopEntryPath(), self) + fcdesk.setGeometry(x + 120, y + 40, 100, 20) + fcacclbl = Qt::Label.new("accuracy", self) + fcacclbl.setGeometry(x + 15, y + 60, 100, 20) + fcacc = Qt::Label.new(acc.to_s, self) + fcacc.setGeometry(x + 120, y + 60, 150, 20) + end +end + + +#-------------------- main ------------------------------------------------ + +description = "Test/demo KSharedPtr related methods/classes" +version = "1.0" +aboutData = KDE::AboutData.new("mimetype", "MimeType", + version, description, KDE::AboutData.License_GPL, + "(C) 2003 Jim Bublitz") + +KDE::CmdLineArgs.init(ARGV, aboutData) + +KDE::CmdLineArgs.addCmdLineOptions([["+files", "File to open", ""]]) + +app = KDE::Application.new() +mainWindow = MainWin.new(nil, "main window") +mainWindow.show() +app.exec() diff --git a/korundum/rubylib/examples/rbKHTMLPart.rb b/korundum/rubylib/examples/rbKHTMLPart.rb new file mode 100644 index 00000000..e3beb927 --- /dev/null +++ b/korundum/rubylib/examples/rbKHTMLPart.rb @@ -0,0 +1,217 @@ +=begin +This is a ruby version of Jim Bublitz's pykde program, translated by Richard Dale +=end + +# +# pyParts.py (C) 2002 Jim Bublitz <jbublitz@nwinternet.com> +# + +=begin + +This is an extemely simple and crude example of using +a KHTMLPart - I put it together mostly to make sure +the openURL method worked correctly after some modifications +done in KParts::ReadOnlyPart. It took exactly four lines +added to a basic Korundum app framework to display a URL +via the 'net: + + w = KDE::HTMLPart.new(self, "HTMLPart", self) + w.openURL(KDE::URL.new("http://www.kde.org")) + w.view().setGeometry(30, 55, 500, 400) + w.show() + +You can play around with the commented out lines or add +additional code to make this do something useful. The +.rc for khtnmlpart (sorry, I never looked it up), doesn't +seem to provide much help. Also, to follow links, you +probably need to connect some signals to slots. I +haven't tried it, but this should work with a plain +KMainWindow or other widget too. + +The KDE website also incorporates gifs, jpegs, and +I believe CSS too. Playing around with some other +sites, it appears the font defaults could use some +improvement. + +NOTE!!! For this to work, you (obviously) need to have +a route to the internet established or specify a local +URL - PyKDE/KDE will take care of everything else. + +Perceptive users will notice the KHTMLPart code is +lifted from the KDE classref. + +=end + +require 'Korundum' + +# Note that we use KParts.MainWindow, not KMainWindow as the superclass +# (KParts.MainWindow subclasses KMainWindow). Also, be sure the 'apply' +# clause references KParts.MainWindow - it's a hard bug to track down +# if it doesn't. + +class RbPartsMW < KParts::MainWindow + slots 'close()', 'optionsShowToolbar()', 'optionsShowStatusbar()', 'optionsConfigureKeys()', + 'optionsConfigureToolbars()' + + TOOLBAR_EXIT = 0 + TOOLBAR_OPEN = 1 + + def initialize(*k) + super + + # Create the actions for our menu/toolbar to use + # Keep in mind that the part loaded will provide its + # own menu/toolbar entries + + # check out KParts.MainWindow's ancestry to see where + # some of this and later stuff (like self.actionCollection () ) + # comes from + + quitAction = KDE::StdAction.quit(self, SLOT('close()'), actionCollection()) + + createStandardStatusBarAction() +# @m_toolbarAction = KDE::StdAction.showToolbar(self, SLOT('optionsShowToolbar()'), actionCollection()) + @m_statusbarAction = KDE::StdAction.showStatusbar(self, SLOT('optionsShowStatusbar()'), actionCollection()) + + KDE::StdAction.keyBindings(self, SLOT('optionsConfigureKeys()'), actionCollection()) + KDE::StdAction.configureToolbars(self, SLOT('optionsConfigureToolbars()'), actionCollection()) + + path = Dir.getwd() + '/' + setGeometry(0, 0, 600, 500) + + # point to our XML file + setXMLFile(path + "rbParts.rc", false) + + # The next few lines are all that's necessary to + # create a web browser (of course you have to edit + # this file to change url's) + + w = KDE::HTMLPart.new(self, "HTMLPart", self) + w.openURL(KDE::URL.new("http://www.kde.org")) + + w.view().setGeometry(30, 55, 500, 400) + + +# self.v = KHTMLView (self.w, self) + +# self.setCentralWidget (self.v) + +# self.createGUI (self.w) + + w.show() + end + + + + + # slots for our actions + def optionsShowToolbar() + if @m_toolbarAction.isChecked() + toolBar().show() + else + toolBar().hide() + end + end + + def optionsShowStatusbar() + if @m_statusbarAction.isChecked() + statusBar().show() + else + statusBar().hide() + end + end + + + def optionsConfigureKeys() + KDE::KeyDialog.configureActionKeys(actionCollection(), xmlFile()) + end + + + def optionsConfigureToolbars() + dlg = KDE::EditToolbar.new(actionCollection(), xmlFile()) + if dlg.exec() + createGUI(self) + end + end + + + # some boilerplate left over from pyKLess/KLess + def queryClose() + res = KDE::MessageBox.warningYesNoCancel(self, + i18n("Save changes to Document?<br>(Does not make sense, we know, but it is just a programming example :-)")) + if res == KDE::MessageBox::Yes + #// save document here. If saving fails, return FALSE + return true + + elsif res == KDE::MessageBox::No + return true + + else #// cancel + return false + end + end + + def queryExit() + #// this slot is invoked in addition when the *last* window is going + #// to be closed. We could do some final cleanup here. + return true #// accept + end + + # I'm not sure the session mgmt stuff here works + + # Session management: save data + def saveProperties(config) + # This is provided just as an example. + # It is generally not so good to save the raw contents of an application + # in its configuration file (as this example does). + # It is preferable to save the contents in a file on the application's + # data zone and save an URL to it in the configuration resource. + config.writeEntry("text", edit.text()) + end + + + # Session management: read data again + def readProperties(config) + # See above + edit.setText(config.readEntry("text")) + end +end + + +#------------- main ---------------------------- + +# A Human readable description of your program +description = "KHTMLPart - simple example" +# The version +version = "0.1" + +# stuff for the "About" menu +aboutData = KDE::AboutData.new("rbKHTMLPart", "rbHTMLPart", + version, description, KDE::AboutData::License_GPL, + "(c) 2002, Jim Bublitz") + +aboutData.addAuthor("Jim Bublitz", "Example for PyKDE", "jbublitz@nwinternet.com") +aboutData.addAuthor('Richard Dale', 'Example for Korundum', 'Richard_Dale@tipitina.demon.co.uk') + +# This MUST go here (before KApplication () is called) +KDE::CmdLineArgs.init(ARGV, aboutData) + +app = KDE::Application.new() + +if app.isRestored() + KDE::MainWindow.kRestoreMainWindows(RbPartsMW) +else + # no session management: just create one window + # this is our KParts::MainWindow derived class + parts = RbPartsMW.new(nil, "rbParts") + if ARGV.length > 1 + # read kcmdlineargs.h for the full unabridged instructions + # on using KCmdLineArgs, it's pretty confusing at first, but it works + # This is pretty useless in this program - you might want to + # expand this in your app (to load a file, etc) + args = KDE::CmdLineArgs.parsedArgs() + end +end + +parts.show() +app.exec() diff --git a/korundum/rubylib/examples/rbtestimage.png b/korundum/rubylib/examples/rbtestimage.png Binary files differnew file mode 100644 index 00000000..550371b1 --- /dev/null +++ b/korundum/rubylib/examples/rbtestimage.png diff --git a/korundum/rubylib/examples/systray.rb b/korundum/rubylib/examples/systray.rb new file mode 100644 index 00000000..85b27366 --- /dev/null +++ b/korundum/rubylib/examples/systray.rb @@ -0,0 +1,66 @@ +=begin +This is a ruby version of Jim Bublitz's pykde program, translated by Richard Dale +=end + +=begin +Copyright 2003 Jim Bublitz + +Terms and Conditions + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +Except as contained in this notice, the name of the copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in this Software without prior written authorization from the +copyright holder. +=end + +require 'Korundum' + +class MainWin < KDE::MainWindow + def initialize(*args) + super + end +end + +#-------------------- main ------------------------------------------------ + +appName = "template" + +aboutData = KDE::AboutData.new("systry", "Systray test",\ + "0.1", "Systray test", KDE::AboutData::License_GPL,\ + "(c) 2002, Jim Bublitz") + +aboutData.addAuthor('Jim Bublitz', 'Example for PyKDE', 'jbublitz@nwinternet.com') +aboutData.addAuthor('Richard Dale', 'For Korundum', 'Richard_Dale@tipitina.demon.co.uk') + +# This MUST go here (before KApplication () is called) +KDE::CmdLineArgs.init(ARGV, aboutData) +app = KDE::Application.new() +mainWindow = MainWin.new(nil, "main window") +icons = KDE::IconLoader.new() + +systray = KDE::SystemTray.new(mainWindow) +systray.setPixmap(icons.loadIcon("stop", 0)) +systray.show() + +#mainWindow.show() +app.exec() + + diff --git a/korundum/rubylib/examples/uikmdi.rb b/korundum/rubylib/examples/uikmdi.rb new file mode 100644 index 00000000..df7d0e1d --- /dev/null +++ b/korundum/rubylib/examples/uikmdi.rb @@ -0,0 +1,187 @@ + +=begin +This is a ruby version of Jim Bublitz's python original. The ruby behaviour +is 'crash for crash' identical - so the the problems described below are +related to KMDI, and not the bindings. +=end + +=begin +A rough Python translation of the ideas presented in this KMDI tutorial: + + http://web.tiscali.it/andreabergia/kmditutorial.html + +What does work: + + IDEAlMode - yay! + + Adding and closing child views + + Two-way syncing between a tool widget and a matching child view + +All is not rosy, however: + + Instances of the KmdiExample maintain a dictionary of child views. Values + cannot be deleted from this dictionary during a window close (causes an + immediate segfault). + + Child views created after initialization aren't numbered correctly; given + the first problem, it's harder to do this than it's really worth. + + The example segfaults at shutdown if the tool (on the left) is is open but + is not in overlap-mode. + +=end + +require 'Korundum' +include KDE + +class KmdiExample < KDE::MdiMainFrm + + slots 'closeChild(KMdiChildView*)', + 'syncFromChildView(KMdiChildView*)', + 'syncFromMainTool(QListBoxItem*)', + 'activatedMessage(KMdiChildView*)', + 'newView()', 'close()', 'closeActiveChild()' + + def getIcon(name, group=Icon::NoGroup, size=Icon::SizeSmall) + # returns a kde icon by name + return Global.instance().iconLoader().loadIcon(name, group, size) + end + + def initialize(parent=nil) + super(parent, 'KmdiExample', Mdi::IDEAlMode) + + @viewIcons = ['network', 'email', 'stop', 'back', 'forward'] + @toolIcons = ['view_icon', 'configure'] + + openNewAction = StdAction.openNew(self, SLOT('newView()'), actionCollection()) + quitAction = StdAction.quit(self, SLOT('close()'), actionCollection()) + closeAction = StdAction.close(self, SLOT('closeActiveChild()'), actionCollection()) + + uifilebase = Dir.getwd + '/uikmdi.rc' + createGUI(uifilebase) + # The task bar is created in the KMdiMainFrm constructor + # and then deleted in the createGUI() call above.. + # So recreate it again to avoid a crash. + createTaskBar() + statusBar() + resize(400, 300) + + @tools = {} + @toolIcons.each_index do |idx| + ico = @toolIcons[idx] + wid = KDE::ListBox.new(self, "list#{idx.to_s}") + makeTool(wid, "Tool #{idx.to_s}", ico) + end + ## smells + @mainToolWidget = @maintool = @tools['Tool 0'][0] + + @childs = {} + @viewIcons.each_index do |idx| + ico = @viewIcons[idx] + makeView("View #{idx.to_s}", ico, ico) + end + + connect(self, SIGNAL('viewActivated(KMdiChildView*)'), self, SLOT('activatedMessage(KMdiChildView*)')) + connect(self, SIGNAL('viewActivated(KMdiChildView*)'), self, SLOT('syncFromChildView(KMdiChildView*)')) + connect(@maintool, SIGNAL('selectionChanged(QListBoxItem*)'), self, SLOT('syncFromMainTool(QListBoxItem*)')) + syncFromChildView(activeWindow()) + end + + def syncFromMainTool(item) + # activate the view that matches the item text + activateView(findWindow(item.text())) + end + + def syncFromChildView(child) + # sync the main tool to the indicated child + @maintool = @mainToolWidget + if child.nil? + return + end + item = @maintool.findItem(child.tabCaption()) + if !item.nil? + @maintool.setSelected(item, nil) + end + end + + def makeTool(widget, caption, icon, percent=50) + # makes a tool from the widget + tip = i18n("#{caption} Tool Tip") + dock = DockWidget::DockLeft + maindock = getMainDockWidget() + widget.setIcon(getIcon(icon)) + tool = addToolWindow(widget, dock, maindock, percent, tip, caption) + @tools[caption] = [widget, tool] + end + + def makeView(label, icon, text) + # makes a child view with a text label and a pixmap label + view = MdiChildView.new(label, self) + @childs[label] = view + view.setIcon(getIcon(icon)) + layout = Qt::VBoxLayout.new(view) + layout.setAutoAdd(true) + + lbl = Qt::Label.new(i18n("Label for a view with an icon named #{text}"), view) + pxm = Qt::Label.new('', view) + pxm.setPixmap(getIcon(icon, Icon::NoGroup, KDE::Icon::SizeLarge)) + addWindow(view) + @mainToolWidget.insertItem(label) + connect(view, SIGNAL('childWindowCloseRequest(KMdiChildView*)'), self, SLOT('closeChild(KMdiChildView*)')) + end + + def removeMainToolItem(view) + # remove item from the main list tool that corresponds to the view + @maintool = @mainToolWidget + @maintool.takeItem(@maintool.findItem(view.tabCaption(), 0)) + end + + def newView() + # make a view when the user invokes the new action + makeView("View ", 'network', 'A Fresh View') +# makeView("View #{@childs.length}", 'network', 'A Fresh View') + syncFromChildView(activeWindow()) + end + + def closeActiveChild() + # close the current view + removeMainToolItem(activeWindow()) + closeActiveView() + syncFromChildView(activeWindow()) + end + + def closeChild(which) + # called to close a view from its tab close button + caption = which.tabCaption() + removeMainToolItem(which) + which.close() + statusBar().message(i18n("#{caption} closed")) + syncFromChildView(activeWindow()) + end + + def activatedMessage(view) + # updates the status bar with the caption of the current view + statusBar().message(i18n("#{view.tabCaption()} activated")) + end +end + +if $0 == __FILE__ + aname = 'uikmdi' + desc = 'A Simple Korundum KMDI Sample' + ver = '1.0' + lic = AboutData::License_GPL + author = 'Troy Melhase' + authormail = 'troy@gci.net' + + about = AboutData.new(aname, aname, ver, desc, lic, "#{authormail} (c) 2004") + about.addAuthor(author, 'hi, mom!', authormail) + about.addAuthor('Jim Bublitz', 'For PyKDE', 'jbublitz@nwinternet.com') + about.addAuthor('Richard Dale', 'For Korundum', 'Richard_Dale@tipitina.demon.co.uk') + CmdLineArgs.init(ARGV, about) + app = KDE::Application.new + mainWindow = KmdiExample.new + mainWindow.show + app.exec +end + diff --git a/korundum/rubylib/examples/uikmdi.rc b/korundum/rubylib/examples/uikmdi.rc new file mode 100644 index 00000000..a7e21969 --- /dev/null +++ b/korundum/rubylib/examples/uikmdi.rc @@ -0,0 +1,11 @@ +<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"> +<kpartgui name="testfoo" version="1"> +<MenuBar> + +<!-- <Menu name="custom"><text>C&ustom</text> + <Action name="custom_action" /> + </Menu> +--> + +</MenuBar> +</kpartgui> diff --git a/korundum/rubylib/examples/uimodules/uidialogs.rb b/korundum/rubylib/examples/uimodules/uidialogs.rb new file mode 100644 index 00000000..2d264a4b --- /dev/null +++ b/korundum/rubylib/examples/uimodules/uidialogs.rb @@ -0,0 +1,256 @@ +=begin +This is a ruby version of Jim Bublitz's pykde program, translated by Richard Dale +=end + +require 'Korundum' + +module UIDialogs + +class CustomDlg < KDE::Dialog + + slots 'dlgClicked()', 'okClicked()', 'cancelClicked()' + + def initialize(parent, name = "custom dlg", modal = false) + super(parent, name, modal) + + x = 20 + y = 10 + + rLbl = Qt::Label.new("r", self) + gLbl = Qt::Label.new("g", self) + bLbl = Qt::Label.new("b", self) + @rEd = Qt::LineEdit.new("64", self) + @gEd = Qt::LineEdit.new("64", self) + @bEd = Qt::LineEdit.new("64", self) + dlgBtn = Qt::PushButton.new("Set/Get Color", self) + okBtn = Qt::PushButton.new("OK", self) + canBtn = Qt::PushButton.new("Cancel", self) + + rLbl.setGeometry(x, y, 25, 20) + gLbl.setGeometry(x + 30, y, 25, 20) + bLbl.setGeometry(x + 60, y, 25, 20) + y = y + 20 + @rEd.setGeometry(x, y, 25, 20) + @gEd.setGeometry(x + 30, y, 25, 20) + @bEd.setGeometry(x + 60, y, 25, 20) + y = y + 30 + dlgBtn.setGeometry(x, y, 90, 22) + y = y + 30 + okBtn.setGeometry(x, y, 40, 22) + canBtn.setGeometry(x + 50, y, 40, 22) + + connect(dlgBtn, SIGNAL("clicked()"), SLOT('dlgClicked()')) + connect(okBtn, SIGNAL("clicked()"), SLOT('okClicked()')) + connect(canBtn, SIGNAL("clicked()"), SLOT('cancelClicked()')) + end + + def dlgClicked() + # get some(numerical) color values from the original dialog + red = @rEd.text().to_i + green = @gEd.text().to_i + blue = @bEd.text().to_I + + # convert the numbers to a Qt::Color + color = Qt::Color.new(red, green, blue) + + # invoke the dialog(getColor is a 'static' call) + # initialize with the colors from above(in color) + # color will also hold the new value chosen in the + # KDE::ColorDialog + result = KDE::ColorDialog.getColor(color, self) + + # get the numerical color values back +# red, green, blue = color.rgb() + + # update the Qt::LineEdits in the original dialog + @rEd.setText(red.to_s) + @gEd.setText(green.to_s) + @bEd.setText(blue.to_s) + end + + def okClicked() + done(1) + end + + def cancelClicked() + done(0) + end +end + +class MessageDlg < KDE::Dialog + + slots 'launch(int)' + + def initialize(parent, name = "message dlg", modal = false) + super(parent, name, modal) + + buttons = ["QuestionYesNo", "WarningYesNo", "WarningContinueCancel", "WarningYesNoCancel", + "Information", "SSLMessageBox", "Sorry", "Error", "QuestionYesNoCancel"] + + n = buttons.length + + grp = Qt::ButtonGroup.new(n, Qt::Vertical, "MessageBoxes", self, "button grp") + grp.setGeometry(10, 10, 200, 30*n) + (0...n).each { |i| Qt::RadioButton.new(buttons[i], grp) } + + connect(grp, SIGNAL("clicked(int)"), SLOT('launch(int)')) + end + + def launch(which) + which += 1 # Qt::ButtonGroup id's start at 0, but the KDE::MessageBox enum starts at 1 + + if which == KDE::MessageBox::QuestionYesNo + KDE::MessageBox.questionYesNo(self, "This is a questionYesNo message box\nThere is also a list version of this dialog",\ + "questionYesNo") + + elsif which == KDE::MessageBox::WarningYesNo + KDE::MessageBox.warningYesNo(self, "This is a warningYesNo message box", "warningYesNo") + + elsif which == KDE::MessageBox::WarningContinueCancel + KDE::MessageBox.warningContinueCancel(self, "This is a warningContinueCancel message box", "warningContinueCancel"); + + elsif which == KDE::MessageBox::WarningYesNoCancel + KDE::MessageBox.warningYesNoCancel(self, "This is a warningYesNoCancel message box", "warningYesNoCancel") + + elsif which == KDE::MessageBox::Information + KDE::MessageBox.information(self, "This is an information message box", "Information") + +# elsif which == KDE::MessageBox::SSLMessageBox +# KDE::MessageBox.SSLMessageBox(self, "This is an SSLMessageBox message box", "not implemented yet") + + elsif which == KDE::MessageBox::Sorry + KDE::MessageBox.sorry(self, "This is a 'sorry' message box", "Sorry") + + elsif which == KDE::MessageBox::Error + KDE::MessageBox.error(self, "No - this isn't really an error\nIt's an error message box\n", "Error") + + elsif which == KDE::MessageBox::QuestionYesNoCancel + KDE::MessageBox.questionYesNoCancel(self, "No - this isn't really an error\nIt's an QuestionYesNoCancel message box\n", "QuestionYesNoCancel") + end + end +end + + +def UIDialogs.dlgKAboutDialog(parent) + dlg = KDE::AboutDialog.new(parent, 'about dialog', false) + dlg.setLogo(Qt::Pixmap.new("rbtestimage.png")) + dlg.setTitle("UISampler for Korundum") + dlg.setAuthor("Jim Bublitz", "jbublitz@nwinternet.com", "http://www.riverbankcomputing.co.uk", + "\n\nPyKDE -- Python bindings\n\tfor KDE") + dlg.setMaintainer("Richard Dale", "Richard_Dale@tipitina.demon.co.uk", "http://developer.kde.org/language-bindings/ruby/",\ + "\n\nKorundum -- Ruby bindings\n\tfor KDE") + dlg.addContributor("KDE bindings list", "kde-bindings@kde.org", nil, nil) + + dlg.show() +end + + +def UIDialogs.dlgKBugReport(parent) + dlg = KDE::BugReport.new(parent) + dlg.exec() +end + +def UIDialogs.dlgKAboutKDE(parent) + dlg = KDE::AboutKDE.new(parent, "about kde", false) + dlg.show() +end + +def UIDialogs.dlgKColorDialog(parent) + dlg = KDE::ColorDialog.new(parent, "color dlg", false) + dlg.show() +end + +def UIDialogs.dlgKDialog(parent) + dlg = CustomDlg.new(parent) + dlg.show() +end + +def UIDialogs.dlgKDialogBase(parent) + caption = "KDialogBase sample" + text_ = "This is a KDialogBase example" + dlg = KDE::DialogBase.new(parent, "sample_dialog", false, caption, + KDE::DialogBase::Ok | KDE::DialogBase::Cancel, KDE::DialogBase::Ok, true ) + + page = dlg.makeVBoxMainWidget(); + + # making 'page' the parent inserts the widgets in + # the VBox created above + label = Qt::Label.new( caption, page, "caption" ); + + lineedit = Qt::LineEdit.new(text_, page, "lineedit" ); + lineedit.setMinimumWidth(dlg.fontMetrics().maxWidth()*20); + + label0 = Qt::Label.new("Border widths", page) +# widths = dlg.getBorderWidths() +# labelA = Qt::Label.new("Upper Left X: " + widths[0].to_s, page) +# labelB = Qt::Label.new("Upper Left Y: " + widths[0].to_s, page) +# labelC = Qt::Label.new("Lower Right X: " + str(c), page) +# labelD = Qt::Label.new("Lower Right Y: " + str(d), page) + + dlg.show() +end + +def UIDialogs.dlgKFontDialog(parent) + dlg = KDE::FontDialog.new(parent, "font dlg", false, false) + dlg.show() +end + +def UIDialogs.dlgKKeyDialog(parent) + # This really doesn't do anything except pop up the dlg + keys = KDE::Accel.new(parent) +# keys.insertItem( i18n( "Zoom in" ), "Zoom in", "+" ) + keys.readSettings(); + KDE::KeyDialog.configure(keys, true) +end + +def UIDialogs.dlgKInputDialog(parent) + ok = Qt::Boolean.new + result = KDE::InputDialog.getText("Enter text", "", "<Your input here>", ok) +# puts "result: %s" % result +# puts "ok: %s" % ok + + # pop up another dlg to show what happened in the KDE::LineEditDlg + if !ok.nil? + KDE::MessageBox.information(parent, "OK was pressed\nText: " + result, "KDE::InputDialog result") + else + KDE::MessageBox.information(parent, "Cancel pressed\nText", "KDE::InputDialog result") + end +end + +def UIDialogs.dlgKMessageBox(parent) + dlg = MessageDlg.new(parent) + dlg.show() +end + +def UIDialogs.dlgKPasswordDialog(parent) + password = "" + result = KDE::PasswordDialog.getPassword(password, "Enter password(just a test)") + puts "password: #{password}" +end + +def UIDialogs.dlgKWizard(parent) + wiz = KDE::Wizard.new(parent) + + page1 = Qt::Widget.new(wiz) + p1Lbl = Qt::Label.new("This is page 1", page1) + p1Lbl.setGeometry(20, 20, 100, 20) + page2 = Qt::Widget.new(wiz) + p2Lbl = Qt::Label.new("This is page 2", page2) + p2Lbl.setGeometry(50, 20, 100, 20) + page3 = Qt::Widget.new(wiz) + p3Lbl = Qt::Label.new("This is page 3", page3) + p3Lbl.setGeometry(80, 20, 100, 20) + + wiz.addPage(page1, "Page 1") + wiz.addPage(page2, "Page 2") + wiz.addPage(page3, "Page 3") + wiz.show() +end + +if $0 == __FILE__ + puts + puts "Please run uisampler.rb" + puts +end + +end diff --git a/korundum/rubylib/examples/uimodules/uimenus.rb b/korundum/rubylib/examples/uimodules/uimenus.rb new file mode 100644 index 00000000..4a8ff523 --- /dev/null +++ b/korundum/rubylib/examples/uimodules/uimenus.rb @@ -0,0 +1,137 @@ +=begin +This is a ruby version of Jim Bublitz's pykde program, translated by Richard Dale +=end + +require 'Korundum' + +module UIMenus + +class PageLaunch + def initialize(parent) + page = parent.addPage() + + x = 10 + y = 10 + + launchLbl = Qt::Label.new("Launching application ... please wait\n\nClose launched application to continue", page) + launchLbl.setGeometry(x, y, 300, 80) + launchLbl.show() + + page.show() + + $kapp.processEvents() + end +end + + +class PageNotImpl + def initialize(parent) + page = parent.addPage() + + x = 10 + y = 10 + + niLbl = Qt::Label.new("Nothing is currently implemented for this widget", page) + niLbl.setGeometry(x, y, 300, 20) + niLbl.show() + end +end + +def UIMenus.menuKAccelGen(parent) + parent.currentPageObj = PageNotImpl.new(parent) +end + +def UIMenus.menuKAccelMenu(parent) + parent.currentPageObj = PageNotImpl.new(parent) +end + +def UIMenus.menuKAction(parent) + parent.currentPageObj = PageLaunch.new(parent) + system("ruby menudemo.rb") +end + +def UIMenus.menuKActionMenu(parent) + parent.currentPageObj = PageLaunch.new(parent) + system("ruby menudemo.rb") +end + +def UIMenus.menuKActionSeparator(parent) + parent.currentPageObj = PageLaunch.new(parent) + system("ruby menudemo.rb") +end + +def UIMenus.menuKContextMenuManager(parent) +# pass +end + +def UIMenus.menuKDCOPActionProxy(parent) +# pass +end + +def UIMenus.menuKHelpMenu(parent) + parent.currentPageObj = PageLaunch.new(parent) + system("ruby menudemo.rb") +end + +def UIMenus.menuKMenuBar(parent) + parent.currentPageObj = PageLaunch.new(parent) + system("ruby menudemo.rb") +end + +def UIMenus.menuKPanelApplet(parent) + parent.currentPageObj = PageNotImpl.new(parent) +end + +def UIMenus.menuKPanelExtension(parent) + parent.currentPageObj = PageNotImpl.new(parent) +end + +def UIMenus.menuKPanelMenu(parent) + parent.currentPageObj = PageNotImpl.new(parent) +end + +def UIMenus.menuKPopupFrame(parent) +# pass +end + +def UIMenus.menuKPopupMenu(parent) +# pass +end + +def UIMenus.menuKPopupTitle(parent) +# pass +end + +def UIMenus.menuKStatusBar(parent) + parent.currentPageObj = PageLaunch.new(parent) + system("ruby menudemo.rb") +end + +def UIMenus.menuKStatusBarLabel(parent) + parent.currentPageObj = PageLaunch.new(parent) + system("ruby menudemo.rb") +end + +def UIMenus.menuKStdAction(parent) + parent.currentPageObj = PageLaunch.new(parent) + system("ruby menudemo.rb") +end + +def UIMenus.menuKToolBar(parent) + parent.currentPageObj = PageLaunch.new(parent) + system("ruby menudemo.rb") +end + +def UIMenus.menuKWindowListMenu(parent) +# pass +end + + +if $0 == __FILE__ + puts + puts "Please run uisampler.rb" + puts +end + +end + diff --git a/korundum/rubylib/examples/uimodules/uimisc.rb b/korundum/rubylib/examples/uimodules/uimisc.rb new file mode 100644 index 00000000..f9d70161 --- /dev/null +++ b/korundum/rubylib/examples/uimodules/uimisc.rb @@ -0,0 +1,273 @@ +=begin +This is a ruby version of Jim Bublitz's pykde program, translated by Richard Dale +=end + +require 'Korundum' + +module UIMisc + +class Page3 < Qt::Object + slots 'ivChanged()', 'fvChanged()', 'dvChanged()' + + def initialize(parent) + super + page = parent.addPage() + x = 10 + y = 15 + + green = Qt::Color.new(0, 255, 0) + yellow = Qt::Color.new(255, 255, 0) + red = Qt::Color.new(255, 0, 0) + + ivLbl = Qt::Label.new("KIntValidator", page) + ivLbl.setGeometry(x, y, 100, 20) + ivLbl.show() + + @iv = KDE::LineEdit.new(page) + @iv.setGeometry(x, y + 20, 100, 20) + @iv.show() + connect(@iv, SIGNAL("textChanged(const QString&)"), SLOT('ivChanged()')) + + @ivVal = KDE::IntValidator.new(page) + @ivVal.setRange(20, 50) + + ivRngLbl = Qt::Label.new("Range is 20 - 50", page) + ivRngLbl.setGeometry(x, y + 45, 100, 20) + ivRngLbl.show() + + ivAccLbl = Qt::Label.new("Acceptable", page) + ivAccLbl.setGeometry(x + 125, y + 45, 85, 20) + ivAccLbl.show() + ivInterLbl = Qt::Label.new("Intermediate", page) + ivInterLbl.setGeometry(x + 125, y + 20, 85, 20) + ivInterLbl.show() + ivInvalLbl = Qt::Label.new("Invalid", page) + ivInvalLbl.setGeometry(x + 125, y - 5, 85, 20) + ivInvalLbl.show() + @ivInvalLed = KDE::Led.new(red, KDE::Led::Off, KDE::Led::Sunken, KDE::Led::Circular,page) + @ivInvalLed.setGeometry(x + 215, y - 5, 18, 18) + @ivInvalLed.show() + @ivInterLed = KDE::Led.new(yellow, KDE::Led::Off, KDE::Led::Sunken, KDE::Led::Circular,page) + @ivInterLed.setGeometry(x + 215, y + 20, 18, 18) + @ivInterLed.show() + @ivAccLed = KDE::Led.new(green, KDE::Led::On, KDE::Led::Sunken, KDE::Led::Circular,page) + @ivAccLed.setGeometry(x + 215, y + 45, 18, 18) + @ivAccLed.show() + + y = y + 100 + + fvLbl = Qt::Label.new("KDoubleValidator", page) + fvLbl.setGeometry(x, y, 100, 20) + fvLbl.show() + + @fv = KDE::LineEdit.new(page) + @fv.setGeometry(x, y + 20, 100, 20) + @fv.show() + connect(@fv, SIGNAL("textChanged(const QString&)"), SLOT('fvChanged()')) + + @fvVal = KDE::DoubleValidator.new(page) + @fvVal.setRange(10.0, 40.0) + + fvRngLbl = Qt::Label.new("Range is 10.0 - 40.0", page) + fvRngLbl.setGeometry(x, y + 45, 100, 20) + fvRngLbl.show() + + fvAccLbl = Qt::Label.new("Acceptable", page) + fvAccLbl.setGeometry(x + 125, y + 45, 85, 20) + fvAccLbl.show() + fvInterLbl = Qt::Label.new("Intermediate", page) + fvInterLbl.setGeometry(x + 125, y + 20, 95, 20) + fvInterLbl.show() + fvInvalLbl = Qt::Label.new("Invalid", page) + fvInvalLbl.setGeometry(x + 125, y - 5, 85, 20) + fvInvalLbl.show() + @fvInvalLed = KDE::Led.new(red, KDE::Led::Off, KDE::Led::Sunken, KDE::Led::Circular,page) + @fvInvalLed.setGeometry(x + 215, y - 5, 18, 18) + @fvInvalLed.show() + @fvInterLed = KDE::Led.new(yellow, KDE::Led::Off, KDE::Led::Sunken, KDE::Led::Circular,page) + @fvInterLed.setGeometry(x + 215, y + 20, 18, 18) + @fvInterLed.show() + @fvAccLed = KDE::Led.new(green, KDE::Led::On, KDE::Led::Sunken, KDE::Led::Circular,page) + @fvAccLed.setGeometry(x + 215, y + 45, 18, 18) + @fvAccLed.show() + + y = y + 100 + + dvLbl = Qt::Label.new("KDateValidator", page) + dvLbl.setGeometry(x, y, 100, 20) + dvLbl.show() + + @dv = KDE::LineEdit.new(page) + @dv.setGeometry(x, y + 20, 100, 20) + @dv.show() +# connect(dv, SIGNAL("textChanged(const QString&)"), SLOT('dvChanged()')) + + @dvVal = KDE::DateValidator.new(page) +# dvVal.setRange(10.0, 40.0) + +# dvRngLbl = Qt::Label.new("Range is 10.0 - 40.0", page) +# dvRngLbl.setGeometry(x, y + 45, 100, 20) +# dvRngLbl.show() + + dvBtn = Qt::PushButton.new("Validate", page) + dvBtn.setGeometry(x, y + 45, 60, 22) + dvBtn.show() + connect(dvBtn, SIGNAL("clicked()"), SLOT('dvChanged()')) + + dvNoteLbl = Qt::Label.new("Format is locale dependent\nShort date only\nTry DD-MM-YY", page) + dvNoteLbl.setGeometry(x, y + 70, 150, 60) + dvNoteLbl.show() + + dvAccLbl = Qt::Label.new("Acceptable", page) + dvAccLbl.setGeometry(x + 125, y + 45, 85, 20) + dvAccLbl.show() + dvInterLbl = Qt::Label.new("Intermediate", page) + dvInterLbl.setGeometry(x + 125, y + 20, 85, 20) + dvInterLbl.show() + dvInvalLbl = Qt::Label.new("Invalid", page) + dvInvalLbl.setGeometry(x + 125, y - 5, 85, 20) + dvInvalLbl.show() + @dvInvalLed = KDE::Led.new(red, KDE::Led::Off, KDE::Led::Sunken, KDE::Led::Circular,page) + @dvInvalLed.setGeometry(x + 215, y - 5, 18, 18) + @dvInvalLed.show() + @dvInterLed = KDE::Led.new(yellow, KDE::Led::Off, KDE::Led::Sunken, KDE::Led::Circular,page) + @dvInterLed.setGeometry(x + 215, y + 20, 18, 18) + @dvInterLed.show() + @dvAccLed = KDE::Led.new(green, KDE::Led::On, KDE::Led::Sunken, KDE::Led::Circular,page) + @dvAccLed.setGeometry(x + 215, y + 45, 18, 18) + @dvAccLed.show() + end + + def ivChanged() + @ivInvalLed.off() + @ivInterLed.off() + @ivAccLed.off() + + i = Qt::Integer.new(0) + state = @ivVal.validate(@iv.text(), i) + + if state == Qt::Validator::Acceptable + @ivAccLed.on() + elsif state == Qt::Validator::Intermediate + @ivInterLed.on() + else + @ivInvalLed.on() + end + end + + def fvChanged() + @fvInvalLed.off() + @fvInterLed.off() + @fvAccLed.off() + + i = Qt::Integer.new(0) + state = @fvVal.validate(@fv.text(), i) + + if state == Qt::Validator::Acceptable + @fvAccLed.on() + elsif state == Qt::Validator::Intermediate + @fvInterLed.on() + else + @fvInvalLed.on() + end + end + + def dvChanged() + @dvInvalLed.off() + @dvInterLed.off() + @dvAccLed.off() + + i = Qt::Integer.new(0) + state = @dvVal.validate(@dv.text(), i) + + if state == Qt::Validator::Acceptable + @dvAccLed.on() + elsif state == Qt::Validator::Intermediate + @dvInterLed.on() + else + @dvInvalLed.on() + end + end +end + +class PageNotImpl + def initialize(parent) + page = parent.addPage() + + x = 10 + y = 10 + + niLbl = Qt::Label.new("Nothing is currently implemented for this widget", page) + niLbl.setGeometry(x, y, 300, 20) + niLbl.show() + end +end + +def UIMisc.miscKAlphaPainter(parent) + parent.currentPageObj = PageNotImpl.new(parent) +end + +def UIMisc.miscKCModule(parent) + parent.currentPageObj = PageNotImpl.new(parent) +end + +def UIMisc.miscKColor(parent) + parent.currentPageObj = PageNotImpl.new(parent) +end + +def UIMisc.miscKColorDrag(parent) + parent.currentPageObj = PageNotImpl.new(parent) +end + +def UIMisc.miscKCommand(parent) + parent.currentPageObj = PageNotImpl.new(parent) +end + +def UIMisc.miscKCommandHistory(parent) + parent.currentPageObj = PageNotImpl.new(parent) +end + +def UIMisc.miscKDockWindow(parent) + parent.currentPageObj = PageNotImpl.new(parent) +end + +def UIMisc.miscKDoubleValidator(parent) + parent.currentPageObj = Page3.new(parent) +end + +def UIMisc.miscKDateValidator(parent) + parent.currentPageObj = Page3.new(parent) +end + +def UIMisc.miscKIntValidator(parent) + parent.currentPageObj = Page3.new(parent) +end + +def UIMisc.miscKPixmapIO(parent) + parent.currentPageObj = PageNotImpl.new(parent) +end + +def UIMisc.miscKSharedPixmap(parent) + parent.currentPageObj = PageNotImpl.new(parent) +end + +def UIMisc.miscKSystemTray(parent) + KDE::MessageBox.information(parent, "See the systray.rb example in the templates/ subdirectories") +end + +def UIMisc.miscKThemeBase(parent) + parent.currentPageObj = PageNotImpl.new(parent) +end + +def UIMisc.miscQXEmbed(parent) + parent.currentPageObj = PageNotImpl.new(parent) +end + +if $0 == __FILE__ + puts + puts "Please run uisampler.rb" + puts +end + +end + diff --git a/korundum/rubylib/examples/uimodules/uiwidgets.rb b/korundum/rubylib/examples/uimodules/uiwidgets.rb new file mode 100644 index 00000000..8dd79d49 --- /dev/null +++ b/korundum/rubylib/examples/uimodules/uiwidgets.rb @@ -0,0 +1,827 @@ +=begin +This is a ruby version of Jim Bublitz's pykde program, translated by Richard Dale +=end + +require 'Korundum' + +module UIWidgets + +class Page1 < Qt::Object + slots 'restrict(int)' + + def initialize(parent) + super + page = parent.addPage() + + x = 10 + y = 10 + + editLbl = Qt::Label.new("KTextEdit", page) + editLbl.setGeometry(x, y, 50, 20) + editLbl.show() + + textList = ["Now is the winter of our discontent\n", + "made glorious summer by this sun of York;\n", + "and all the clouds that lour'd upon our house\n", + "in the deep bosom of the ocean buried.\n"] + + parent.edit = KDE::TextEdit.new(page) + parent.edit.setGeometry(x, y + 20, 300, 100) + textList.each do |line| + parent.edit.insert(line) + end + parent.edit.show() + + y = y + 125 + searchBtn = Qt::PushButton.new("Search", page) + replaceBtn = Qt::PushButton.new("Replace", page) + gotoBtn = Qt::PushButton.new("GoTo Line", page) + + searchBtn.setGeometry(x, y, 60, 22) + replaceBtn.setGeometry(x + 90, y, 60, 22) + gotoBtn.setGeometry(x + 180, y, 60, 22) + +# page.connect(searchBtn, SIGNAL("clicked()"), parent.edit, SLOT('search()')) +# page.connect(replaceBtn, SIGNAL("clicked()"), parent.edit, SLOT('replace()')) +# page.connect(gotoBtn, SIGNAL("clicked()"), parent.edit, SLOT('doGotoLine()')) + + searchBtn.show() + replaceBtn.show() + gotoBtn.show() + + y = y + 35 + + lineeditLbl = Qt::Label.new("KLineEdit", page) + lineeditLbl.setGeometry(x, y, 70, 20) + lineeditLbl.show() + + lineedit = KDE::LineEdit.new(page) + lineedit.setGeometry(x, y + 20, 100, 20) + lineedit.show() + + intLbl = Qt::Label.new("KIntNumInput", page) + intLbl.setGeometry(x + 195, y + 35, 95, 20) + intLbl.show() + + intNum = KDE::IntNumInput.new(5, page) + intNum.setGeometry(x + 195, y + 55, 175, 50) +# intNum.setSuffix(" GB") +# intNum.setPrefix("hdc ") + intNum.setLabel("Capacity") + intNum.setRange(0, 10, 1, true) + intNum.show() + + y = y + 50 + + dblLbl = Qt::Label.new("KDoubleNumInput", page) + dblLbl.setGeometry(x + 195, y + 80, 115, 20) + dblLbl.show() + + dblNum = KDE::DoubleNumInput.new(page) + dblNum.setValue(2.5) + dblNum.setGeometry(x + 195, y + 100, 175, 50) + dblNum.setLabel("Variable") + dblNum.setRange(0.0, 10.0, 0.5, true) + dblNum.show() + + restricteditLbl = Qt::Label.new("KRestrictedLine", page) + restricteditLbl.setGeometry(x, y, 95, 20) + restricteditLbl.show() + + @restrictlineedit = KDE::RestrictedLine.new(page) + @restrictlineedit.setGeometry(x, y + 20, 100, 20) + @restrictlineedit.show() + + buttons = ["Numbers Only", "Upper Case Only", "Lower Case Only"] + + n = buttons.length + + @validLbl = Qt::Label.new("", page) + @validLbl.setGeometry(x, y + 50, 250, 20) + @validLbl.show() + + grp = Qt::ButtonGroup.new(n, Qt::Vertical, "Select valid chars", page, "button grp") + grp.setGeometry(x, y + 75, 150, 5+30*n) + + (0...n).each { |i| Qt::RadioButton.new(buttons[i], grp) } + + connect(grp, SIGNAL("clicked(int)"), SLOT('restrict(int)')) + + grp.find(0).setChecked(true) + restrict(0) + + grp.show() + + page.show() + $kapp.processEvents() + + y = y + 195 + sqzLbl = Qt::Label.new("This text is too long to fit in the label below", page) + sqzLbl.setGeometry(x, y, 350, 20) + sqzLbl.show() + + sqzLbl1 = Qt::Label.new("KSqueezedTxtLabel:", page) + sqzLbl1.setGeometry(x, y + 20, 120, 20) + sqzLbl1.show() + + squeeze = KDE::SqueezedTextLabel.new("This text is too long to fit in the label below", page) + squeeze.setGeometry(x + 125, y + 20, 125, 20) + squeeze.setBackgroundMode(Qt::Widget::PaletteBase) + squeeze.show() + end + + def restrict(which) + r = {0 => "0123456789", 1 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 2 => "abcdefghijklmnopqrstuvwxyz"} + @restrictlineedit.setValidChars(r[which]) + @validLbl.setText("Valid: " + @restrictlineedit.validChars()) + end +end + +class Page2 + def initialize(parent) + page = parent.addPage() + + x1 = 10 + y1 = 10 + x2 = 240 + y2 = 100 + + cbLbl = Qt::Label.new("KComboBox", page) + cbLbl.setGeometry(x1, y1, 75, 20) + cbLbl.show() + + combo = KDE::ComboBox.new(page) + combo.insertStringList(["One", "Two", "Three"]) + combo.setGeometry(x1, y1 + 20, 100, 25) + combo.show() + + ccbLbl = Qt::Label.new("KColorCombo", page) + ccbLbl.setGeometry(x2, y1, 100, 20) + ccbLbl.show() + + colorCombo = KDE::ColorCombo.new(page) + colorCombo.setGeometry(x2, y1 + 20, 100, 25) + colorCombo.show() + + editListBox = KDE::EditListBox.new("KEditListBox", page) + editListBox.setGeometry(x1, y2, 220, 175) + editListBox.insertStringList(["One", "Two", "Three"]) + editListBox.show() + + lbLbl = Qt::Label.new("KListBox", page) + lbLbl.setGeometry(x2, y2, 100, 20) + lbLbl.show() + + listBox = KDE::ListBox.new(page) + listBox.setGeometry(x2, y2 + 20, 100, 100) + listBox.insertStringList(["One", "Two", "Three"]) + listBox.show() + end +end + +class Page3 + def initialize(parent) + page = parent.addPage() + + x = 10 + y = 10 + + fontLbl = Qt::Label.new("KFontChooser", page) + fontLbl.setGeometry(x, y, 95, 20) + fontLbl.show() + + fontChoose = KDE::FontChooser.new(page) + fontChoose.setGeometry(x, y + 20, 375, 300) + fontChoose.show() + + y = y + 330 + end +end + +class Page4 + def initialize(parent) + page = parent.addPage() + + x = 10 + y = 10 + + cbLbl = Qt::Label.new("KColorButton", page) + cbLbl.setGeometry(x, y, 75, 20) + cbLbl.show() + + cb = KDE::ColorButton.new(page) + cb.setColor(Qt::Color.new(255, 0, 0)) + cb.setGeometry(x, y + 20, 30, 30) + cb.show() + + ccbLbl = Qt::Label.new("KColorCombo", page) + ccbLbl.setGeometry(x + 150, y, 100, 20) + ccbLbl.show() + + colorCombo = KDE::ColorCombo.new(page) + colorCombo.setGeometry(x + 150, y + 20, 100, 25) + colorCombo.show() + + y = y + 60 + + cpLbl = Qt::Label.new("KColorPatch", page) + cpLbl.setGeometry(x, y, 75, 20) + cpLbl.show() + + cp = KDE::ColorPatch.new(page) + cp.setColor(Qt::Color.new(255, 0, 0)) + cp.setGeometry(x, y + 20, 20, 20) + cp.show() + + x = x + 150 + + ccLbl = Qt::Label.new("KColorCells", page) + ccLbl.setGeometry(x, y, 75, 20) + ccLbl.show() + + cc = KDE::ColorCells.new(page, 1, 5) + cc.setColor(0, Qt::Color.new(0, 0, 0)) + cc.setColor(1, Qt::Color.new(255, 0, 0)) + cc.setColor(2, Qt::Color.new(0, 255, 0)) + cc.setColor(3, Qt::Color.new(0, 0, 255)) + cc.setColor(4, Qt::Color.new(255, 255, 255)) + cc.setGeometry(x, y + 20, 100, 20) + cc.show() + + x = 10 + y = y + 50 + + dcLbl = Qt::Label.new("KDualColorButton", page) + dcLbl.setGeometry(x, y, 105, 20) + dcLbl.show() + + dc = KDE::DualColorButton.new(Qt::Color.new(255, 0, 0), Qt::Color.new(0, 0, 0), page) + dc.setGeometry(x, y + 20, 40, 40) + dc.show() + + gsLbl = Qt::Label.new("KGradientSelector", page) + gsLbl.setGeometry(x + 80, y + 30, 110, 20) + gsLbl.show() + + gs = KDE::GradientSelector.new(page) + gs.setGeometry(x + 80, y + 50, 250, 20) + gs.setColors(Qt::Color.new(255, 0, 0), Qt::Color.new(255, 255, 0)) + gs.show() + + y = y + 80 + + hsLbl = Qt::Label.new("KHSSelector", page) + hsLbl.setGeometry(x, y, 95, 20) + hsLbl.show() + + hs = KDE::HSSelector.new(page) + hs.setGeometry(x, y + 20, 350, 80) + hs.show() + + y = y + 110 + + ptLbl = Qt::Label.new("KPaletteTable", page) + ptLbl.setGeometry(x, y, 95, 20) + ptLbl.show() + + pt = KDE::PaletteTable.new(page, 340, 24) + pt.setPalette("Royal") + pt.setGeometry(x, y + 20, 340, 40) + pt.show() + end +end + +class Page5 + def initialize(parent) + page = parent.addPage() + + x = 10 + y = 10 + + rpLbl = Qt::Label.new("KRootPermsIcon", page) + rpLbl.setGeometry(x, y, 95, 20) + rpLbl.show() + + rp = KDE::RootPermsIcon.new(page) + rp.setGeometry(x, y + 20, 32, 32) + rp.show() + + wpLbl = Qt::Label.new("KWritePermsIcon", page) + wpLbl.setGeometry(x + 125, y, 95, 20) + wpLbl.show() + + wp = KDE::WritePermsIcon.new("/usr/bin/gcc", page) + wp.setGeometry(x + 125, y + 20, 32, 32) + wp.show() + + y = y + 75 + + pw1Lbl = Qt::Label.new("KPasswordEdit - echo *", page) + pw1Lbl.setGeometry(x, y, 150, 20) + pw1Lbl.show() + + pw1 = KDE::PasswordEdit.new(KDE::PasswordEdit::OneStar, page, "") + pw1.setGeometry(x, y + 20, 100, 20) + pw1.show() + + y = y + 50 + + pw2Lbl = Qt::Label.new("KPasswordEdit - echo ***", page) + pw2Lbl.setGeometry(x, y, 150, 20) + pw2Lbl.show() + + pw2 = KDE::PasswordEdit.new(KDE::PasswordEdit::ThreeStars, page, "") + pw2.setGeometry(x, y + 20, 100, 20) + pw2.show() + + y = y + 50 + + pw3Lbl = Qt::Label.new("KPasswordEdit - no echo", page) + pw3Lbl.setGeometry(x, y, 150, 20) + pw3Lbl.show() + + pw3 = KDE::PasswordEdit.new(KDE::PasswordEdit::NoEcho, page, "") + pw3.setGeometry(x, y + 20, 100, 20) + pw3.show() + + y = y + 50 + + urlLbl = Qt::Label.new("KURLLabel", page) + urlLbl.setGeometry(x, y, 100, 20) + urlLbl.show() + + url = KDE::URLLabel.new("http://developer.kde.org/language-bindings/ruby/", "Korundum", page) + url.setGeometry(x, y + 20, 100, 20) + url.setUseTips(true) + url.setTipText("http://developer.kde.org/language-bindings/ruby/") + url.show() + + x = 70 + y = y + 50 + + bbLbl = Qt::Label.new("KButtonBox", page) + bbLbl.setGeometry(x, y, 75, 20) + bbLbl.show() + + bbox = KDE::ButtonBox.new(page, Qt::Horizontal) + bbox.setGeometry(x, y + 20, 300, 22) + bbox.addButton("Button 1") + bbox.addButton("Button 2") + bbox.addButton("Button 3") + bbox.show() + + y = y + 50 + +# dbLbl = Qt::Label.new("KDirectionButton", page) +# dbLbl.setGeometry(x, y, 95, 20) +# dbLbl.show() + +# dbUp = KDE::DirectionButton.new(Qt::t::UpArrow, page) +# dbDown = KDE::DirectionButton.new(Qt::t::DownArrow, page) +# dbRight = KDE::DirectionButton.new(Qt::t::RightArrow, page) +# dbLeft = KDE::DirectionButton.new(Qt::t::LeftArrow, page) + +# dbUp.setGeometry(x, y + 20, 22, 22) +# dbDown.setGeometry(x + 30, y + 20, 22, 22) +# dbRight.setGeometry(x + 60, y + 20, 22, 22) +# dbLeft.setGeometry(x + 90, y + 20, 22, 22) + +# dbUp.show() +# dbDown.show() +# dbRight.show() +# dbLeft.show() + + x = x + 150 + +# kbLbl = Qt::Label.new("KKeyButton", page) +# kbLbl.setGeometry(x, y, 95, 20) +# kbLbl.show() + +# kb = KDE::KeyButton.new(page) +# kb.setText("Enter") +# kb.setGeometry(x, y + 20, 50, 32) +# kb.show() + + x = 70 + y = y + 50 + +# tbLbl = Qt::Label.new("KTabButton", page) +# tbLbl.setGeometry(x, y, 95, 20) +# tbLbl.show() + +# tbUp = KDE::TabButton.new(Qt::t::UpArrow, page) +# tbDown = KDE::TabButton.new(Qt::t::DownArrow, page) +# tbRight = KDE::TabButton.new(Qt::t::RightArrow, page) +# tbLeft = KDE::TabButton.new(Qt::t::LeftArrow, page) + +# tbUp.setGeometry(x, y + 20, 22, 25) +# tbDown.setGeometry(x + 30, y + 20, 22, 25) +# tbRight.setGeometry(x + 60, y + 20, 22, 25) +# tbLeft.setGeometry(x + 90, y + 20, 22, 25) + +# tbUp.show() +# tbDown.show() +# tbRight.show() +# tbLeft.show() + end +end + +class Page6 < Qt::Object + slots 'toggleClicked()' + + def initialize(parent) + super + page = parent.addPage() + + x = 20 + y = 10 + + red = Qt::Color.new(255, 0, 0) + green = Qt::Color.new(0, 255, 0) + yellow = Qt::Color.new(255, 255, 0) + blue = Qt::Color.new(0, 0, 255) + + ledcolor = [red, green, yellow, blue] + ledshape = [KDE::Led::Rectangular, KDE::Led::Circular] + ledlook = [KDE::Led::Flat, KDE::Led::Raised, KDE::Led::Sunken] + ledsize = [10, 18, 25] + @ledlist = [] + + ledlook.each do |look| + ledcolor.each do |color| + ledshape.each do |shape| + ledsize.each do |size| + led = KDE::Led.new(color, KDE::Led::On, look, shape, page) + led.setGeometry(x, y, size, size) + @ledlist << led + led.show() + x = x + 50 + end + x = x + 50 + end + x = 20 + y = y + 30 + end + y = y + 10 + end + + toggle = Qt::PushButton.new("Toggle", page) + toggle.setGeometry(150, 400, 60, 22) + toggle.show() + + connect(toggle, SIGNAL("clicked()"), SLOT('toggleClicked()')) + + page.show() + end + + def toggleClicked() + @ledlist.each { |led| led.toggle() } + end +end + +class Page7 < Qt::Object + slots 'add1()' + + def initialize(parent) + super + page = parent.addPage() + + x = 10 + y = 10 + + tabLbl = Qt::Label.new("KTabCtl", page) + tabLbl.setGeometry(x, y, 95, 20) + tabLbl.show() + + tab = KDE::TabCtl.new(page) + tab.setGeometry(x, y + 20, 300, 100) + + page1 = Qt::Widget.new(tab) + p1Lbl = Qt::Label.new("This is page 1", page1) + p1Lbl.setGeometry(20, 20, 100, 20) + page2 = Qt::Widget.new(tab) + p2Lbl = Qt::Label.new("This is page 2", page2) + p2Lbl.setGeometry(50, 20, 100, 20) + page3 = Qt::Widget.new(tab) + p3Lbl = Qt::Label.new("This is page 3", page3) + p3Lbl.setGeometry(20, 50, 100, 20) + + tab.addTab(page1, "Tab 1") + tab.addTab(page2, "Tab 2") + tab.addTab(page3, "Tab 3") + tab.show() + + x = 10 + y = 150 + + progLbl = Qt::Label.new("KProgress", page) + progLbl.setGeometry(x, y + 50, 95, 20) + progLbl.show() + + @p1 = KDE::Progress.new(page) + @p2 = KDE::Progress.new(15, page) + @p1.setTotalSteps(25) + @p2.setTotalSteps(25) + + @p1.setGeometry(x, y + 80, 125, 20) + @p2.setGeometry(x, y + 120, 125, 20) + + @p2.setPercentageVisible(false) + + @p1.show() + @p2.show() + + @total = 0 + + y = y + 150 + sepLbl = Qt::Label.new("KSeparator", page) + sepLbl.setGeometry(x, y, 95, 20) + sepLbl.show() + + sep = KDE::Separator.new(Qt::Frame::HLine, page) + sep.setGeometry(x, y + 20, 75, 10) + sep.show() + + page.show() + + @timer = Qt::Timer.new(page) + connect(@timer, SIGNAL('timeout()'), SLOT('add1()')) + @timer.start(100) + + add1() + end + + def add1() + @total = @total + 1 + @p1.advance(1) + @p2.advance(1) + + if @total == 26 + @timer.stop + end + end +end + +class Page8 + def initialize(parent) + page = parent.addPage() + + x = 40 + y = 10 + + dpLbl = Qt::Label.new("KDatePicker", page) + dpLbl.setGeometry(x, y, 95, 20) + dpLbl.show() + + dp = KDE::DatePicker.new(page) + dp.setGeometry(x, y + 20, 300, 170) + dp.show() + + y = y + 210 + + dtLbl = Qt::Label.new("KDateTable", page) + dtLbl.setGeometry(x, y, 95, 20) + dtLbl.show() + + dt = KDE::DateTable.new(page) + dt.setGeometry(x, y + 20, 300, 130) + dt.show() + end +end + +class PageThisApp + def initialize(parent) + page = parent.addPage() + + x = 10 + y = 10 + + taLbl = Qt::Label.new("This application uses KMainWindow as its top level widget\n and KListView in the"\ + " left-hand panel", page) + taLbl.setGeometry(x, y, 300, 60) + taLbl.show() + end +end + +class PageNotImpl + def initialize(parent) + page = parent.addPage() + + x = 10 + y = 10 + + niLbl = Qt::Label.new("Nothing is currently implemented for this widget", page) + niLbl.setGeometry(x, y, 300, 20) + niLbl.show() + end +end + +class CSDlg < KDE::Dialog + slots 'closeClicked()' + + def initialize(parent, name = "char select dlg", modal = false) + super(parent, name, modal) + + setGeometry(150, 50, 700, 320) + x = 10 + y = 10 + + csLbl = Qt::Label.new("KCharSelect", self) + csLbl.setGeometry(x, y, 95, 20) + csLbl.show() + cs = KDE::CharSelect.new(self, "chselect", nil, Qt::Char.new(0), 0) + cs.setGeometry(x, y + 20, 680, 250) + cs.show() + + closeBtn = Qt::PushButton.new("Close", self) + closeBtn.setGeometry( 610, 280, 60, 22) + closeBtn.show() + + connect(closeBtn, SIGNAL("clicked()"), SLOT('closeClicked()')) + end + + def closeClicked() + done(1) + end +end + +def UIWidgets.widKAnimWidget(parent) + parent.currentPageObj = PageNotImpl.new(parent) +end + +def UIWidgets.widKAuthIcon(parent) + parent.currentPageObj = Page5.new(parent) +end + +def UIWidgets.widKButtonBox(parent) + parent.currentPageObj = Page5.new(parent) +end + +def UIWidgets.widKCharSelect(parent) + dlg = CSDlg.new(parent) + dlg.show() +end + +def UIWidgets.widKColorButton(parent) + parent.currentPageObj = Page4.new(parent) +end + +def UIWidgets.widKColorCells(parent) + parent.currentPageObj = Page4.new(parent) +end + +def UIWidgets.widKColorCombo(parent) + parent.currentPageObj = Page2.new(parent) +end + +def UIWidgets.widKColorPatch(parent) + parent.currentPageObj = Page4.new(parent) +end + +def UIWidgets.widKComboBox(parent) + parent.currentPageObj = Page2.new(parent) +end + +def UIWidgets.widKCompletionBox(parent) + parent.currentPageObj = PageNotImpl.new(parent) +end + +def UIWidgets.widKContainerLayout(parent) + parent.currentPageObj = PageNotImpl.new(parent) +end + +def UIWidgets.widKCursor(parent) + parent.currentPageObj = PageNotImpl.new(parent) +end + +def UIWidgets.widKDatePicker(parent) + parent.currentPageObj = Page8.new(parent) +end + +def UIWidgets.widKDateTable(parent) + parent.currentPageObj = Page8.new(parent) +end + +def UIWidgets.widKDirectionButton(parent) + parent.currentPageObj = Page5.new(parent) +end + +def UIWidgets.widKDualColorButton(parent) + parent.currentPageObj = Page4.new(parent) +end + +def UIWidgets.widKTextEdit(parent) + parent.currentPageObj = Page1.new(parent) +end + +def UIWidgets.widKEditListBox(parent) + parent.currentPageObj = Page2.new(parent) +end + +def UIWidgets.widKFontChooser(parent) + parent.currentPageObj = Page3.new(parent) +end + +def UIWidgets.widKHSSelector(parent) + parent.currentPageObj = Page4.new(parent) +end + +def UIWidgets.widKIconView(parent) + parent.currentPageObj = PageNotImpl.new(parent) +end + +def UIWidgets.widKJanusWidget(parent) + parent.currentPageObj = PageNotImpl.new(parent) +end + +#def UIWidgets.widKKeyButton(parent) +# parent.currentPageObj = Page5.new(parent) + +def UIWidgets.widKKeyChooser(parent) + parent.currentPageObj = PageNotImpl.new(parent) +end + +def UIWidgets.widKLed(parent) + parent.currentPageObj = Page6.new(parent) +end + +def UIWidgets.widKLineEdit(parent) + parent.currentPageObj = Page1.new(parent) +end + +def UIWidgets.widKListBox(parent) + parent.currentPageObj = Page2.new(parent) +end + +def UIWidgets.widKListView(parent) + parent.currentPageObj = PageThisApp.new(parent) +end + +def UIWidgets.widKNumInput(parent) + parent.currentPageObj = Page1.new(parent) +end + +def UIWidgets.widKPaletteTable(parent) + parent.currentPageObj = Page4.new(parent) +end + +def UIWidgets.widKPasswordEdit(parent) + parent.currentPageObj = Page5.new(parent) +end + +def UIWidgets.widKProgress(parent) + parent.currentPageObj = Page7.new(parent) +end + +def UIWidgets.widKRootPixmap(parent) + parent.currentPageObj = PageNotImpl.new(parent) +end + +def UIWidgets.widKMainWindow(parent) + parent.currentPageObj = PageThisApp.new(parent) +end + +def UIWidgets.widKRestrictedLine(parent) + parent.currentPageObj = Page1.new(parent) +end + +def UIWidgets.widKRuler(parent) + parent.currentPageObj = PageNotImpl.new(parent) +end + +def UIWidgets.widKSelector(parent) + parent.currentPageObj = Page4.new(parent) +end + +def UIWidgets.widKSeparator(parent) + parent.currentPageObj = Page7.new(parent) +end + +def UIWidgets.widKSqueezedTextLabel(parent) + parent.currentPageObj = Page1.new(parent) +end + +def UIWidgets.widKTabButton(parent) + parent.currentPageObj = Page5.new(parent) +end + +def UIWidgets.widKTabCtl(parent) + parent.currentPageObj = Page7.new(parent) +end + +def UIWidgets.widKTextBrowser(parent) + parent.currentPageObj = PageNotImpl.new(parent) +end + +def UIWidgets.widKURLLabel(parent) + parent.currentPageObj = Page5.new(parent) +end + + +if $0 == __FILE__ + puts + puts "Please run uisampler.rb" + puts +end + +end diff --git a/korundum/rubylib/examples/uimodules/uixml.rb b/korundum/rubylib/examples/uimodules/uixml.rb new file mode 100644 index 00000000..67be21ac --- /dev/null +++ b/korundum/rubylib/examples/uimodules/uixml.rb @@ -0,0 +1,56 @@ +=begin +This is a ruby version of Jim Bublitz's pykde program, translated by Richard Dale +=end + +require 'Korundum' + +module UIXML + +class PageLaunch + def initialize(parent) + page = parent.addPage() + + x = 10 + y = 10 + + launchLbl = Qt::Label.new("Launching application ... please wait\n\nClose launched application to continue", page) + launchLbl.setGeometry(x, y, 300, 80) + launchLbl.show() + + page.show() + + $kapp.processEvents() + end +end + +def UIXML.xmlKActionCollection(parent) + parent.currentPageObj = PageLaunch.new(parent) + system("ruby xmlmenudemo.rb") +end + +def UIXML.xmlKEditToolbar(parent) + parent.currentPageObj = PageLaunch.new(parent) + system("ruby xmlmenudemo.rb") +end + +def UIXML.xmlKEditToolbarWidget(parent) + parent.currentPageObj = PageLaunch.new(parent) + system("ruby xmlmenudemo.rb") +end + +def UIXML.xmlKXMLGUIBuilder(parent) + parent.currentPageObj = PageLaunch.new(parent) + system("ruby xmlmenudemo.rb") +end + +def UIXML.xmlKXMLGUIClient(parent) + parent.currentPageObj = PageLaunch.new(parent) + system("ruby xmlmenudemo.rb") +end + +def UIXML.xmlKXMLGUIFactory(parent) + parent.currentPageObj = PageLaunch.new(parent) + system("ruby xmlmenudemo.rb") +end + +end diff --git a/korundum/rubylib/examples/uisampler.rb b/korundum/rubylib/examples/uisampler.rb new file mode 100644 index 00000000..10af08de --- /dev/null +++ b/korundum/rubylib/examples/uisampler.rb @@ -0,0 +1,238 @@ +=begin +This is a ruby version of Jim Bublitz's pykde program, translated by Richard Dale +=end + +require 'Korundum' + +require 'uimodules/uiwidgets.rb' +require 'uimodules/uidialogs.rb' +require 'uimodules/uimenus.rb' +require 'uimodules/uimisc.rb' +require 'uimodules/uixml.rb' + +$listItems = {"Dialogs" => + {"KDE::AboutDialog" => ["KDE::AboutApplication", "KDE::AboutContainer", "KDE::ImageTrackLabel", + "KDE::AboutContainerBase", "KDE::AboutContributor", "KDE::AboutWidget"], + "KDE::AboutKDE" => [], + "KDE::BugReport" => [], + "KDE::ColorDialog" => [], + "KDE::Dialog" => [], + "KDE::DialogBase" => ["KDE::DialogBaseButton", "KDE::DialogBase::SButton", "KDE::DialogBaseTile"], + "KDE::FontDialog" => [], + "KDE::KeyDialog" => [], + "KDE::InputDialog" => [], + "KDE::MessageBox" => [], + "KDE::PasswordDialog" => [], + "KDE::Wizard" => []}, + "Widgets" => + {"KDE::AnimWidget" => [], + "KDE::AuthIcon" => ["KDE::RootPermsIcon", "KDE::WritePermsIcon"], + "KDE::ButtonBox" => [], + "KDE::CharSelect" => ["KDE::CharSelectTable"], + "KDE::ColorButton" => [], + "KDE::ColorCells" => [], + "KDE::ColorCombo" => [], + "KDE::ColorPatch" => [], + "KDE::ComboBox" => [], + "KDE::CompletionBox" => [], + "KDE::ContainerLayout" => ["KDE::ContainerLayout::KContainerLayoutItem"], + "KDE::Cursor" => [], + "KDE::DatePicker" => ["KDE::DateInternalMonthPicker", "KDE::DateInternalYearSelector"], + "KDE::DateTable" => [], + "KDE::DualColorButton" => [], + "KDE::EditListBox" => [], + "KDE::FontChooser" => [], + "KDE::HSSelector" => [], + "KDE::IconView" => [], + "KDE::JanusWidget" => ["KDE::JanusWidget::IconListBox"], + "KDE::KeyChooser" => [], + "KDE::Led" => [], + "KDE::LineEdit" => [], + "KDE::ListBox" => [], + "KDE::ListView" => [], + "KDE::NumInput" => ["KDE::DoubleNumInput", "KDE::IntNumInput"], + "KDE::PaletteTable" => [], + "KDE::PasswordEdit" => [], + "KDE::Progress" => [], + "KDE::RootPixmap" => [], + "KDE::MainWindow" => [], + "KDE::RestrictedLine" => [], + "KDE::Ruler" => [], + "KDE::Selector" => ["KDE::GradientSelector", "KDE::ValueSelector", "KDE::HSSelector", "KDE::XYSelector"], + "KDE::Separator" => [], + "KDE::SqueezedTextLabel" => [], + "KDE::TabCtl" => [], + "KDE::TextBrowser" => [], + "KDE::TextEdit" => ["KDE::EdFind", "KDE::EdGotoLine", "KDE::EdReplace"], + "KDE::URLLabel" => []}, + "XML" => + {"KDE::ActionCollection" => [], + "KDE::EditToolbar" => [], + "KDE::EditToolbarWidget" => [], + "KDE::XMLGUIBuilder" => [], + "KDE::XMLGUIClient" => ["KDE::XMLGUIClient::DocStruct"], + "KDE::XMLGUIFactory" => []}, + "Menus/Toolbars" => + {"KDE::AccelMenu" => [], + "KDE::Action" => ["KDE::FontAction", "KDE::FontSizeAction", "KDE::ListAction", "KDE::RecentFilesAction", "KDE::RadioAction", + "KDE::SelectAction", "KDE::ToggleAction"], + "KDE::ActionMenu" => [], + "KDE::ActionSeparator" => [], + "KDE::ContextMenuManager" => [], + "KDE::DCOPActionProxy" => [], + "KDE::HelpMenu" => [], + "KDE::MenuBar" => [], + "KDE::PanelApplet" => [], + "KDE::PanelExtension" => [], + "KDE::PanelMenu" => [], + "KDE::PopupFrame" => [], + "KDE::PopupMenu" => [], + "KDE::PopupTitle" => [], + "KDE::StatusBar" => [], + "KDE::StatusBarLabel" => [], + "KDE::StdAction" => [], + "KDE::ToolBar" => ["KDE::ToolBarButton", "KDE::ToolBarButtonList", "KDE::ToolBarPopupAction", + "KDE::ToolBarRadioGroup", "KDE::ToolBarSeparator"], + "KDE::WindowListMenu" => []}, + "Other" => + {"KDE::AlphaPainter" => [], + "KDE::CModule" => [], + "KDE::Color" => [], + "KDE::ColorDrag" => [], + "KDE::Command" => ["KDE::MacroCommand"], + "KDE::CommandHistory" => [], + "KDE::DateValidator" => [], + "KDE::DockWindow" => ["KDE::DockButton_Private - KPanelMenu", "KDE::DockButton_Private", + "KDE::DockSplitter", "KDE::DockTabCtl_PrivateStruct", "KDE::DockWidgetAbstractHeader", + "KDE::DockWidgetAbstractHeaderDrag", "KDE::DockWidgetHeader", + "KDE::DockWidgetHeaderDrag", "KDE::DockWidgetPrivate"], + "KDE::DoubleValidator" => [], + "KDE::IntValidator" => [], + "KDE::PixmapIO" => [], + "KDE::SharedPixmap" => [], + "KDE::SystemTray" => [], + "KDE::ThemeBase" => ["KDE::ThemeCache", "KDE::ThemePixmap", "KDE::ThemeStyle"], + "QXEmbed" => []}} + +BLANK_MSG = <<END_OF_STRING +<b>UISampler</b> - provides examples of <b>Korundum</b> widgets<p> +Select a dialog/widget/menu/etc example from the tree at left +END_OF_STRING + + +class MainWin < KDE::MainWindow + TREE_WIDTH = 220 + + slots 'lvClicked(QListViewItem*)' + + attr_accessor :edit, :currentPageObj + + def initialize(*args) + super + + setCaption("Samples of Korundum widget usage") + # The following leave about 375 x 390 for the rt hand panel + mainGeom = Qt::Rect.new(0, 0, 640, 500) + setGeometry(mainGeom) + + # create the main view - list view on the left and an + # area to display frames on the right + @mainView = Qt::Splitter.new(self, "main view") + @tree = KDE::ListView.new(@mainView, "tree") + @page = Qt::WidgetStack.new(@mainView, "page") + blankPage = Qt::Widget.new(@page, "blank") + blankPage.setGeometry(0, 0, 375, 390) + blankPage.setBackgroundMode(Qt::Widget::PaletteBase) + + blankLbl = Qt::Label.new(BLANK_MSG, blankPage) + blankLbl.setGeometry(40, 10, 380, 150) + blankLbl.setBackgroundMode(Qt::Widget::PaletteBase) + + blankPM = Qt::Pixmap.new("rbtestimage.png") + pmLbl = Qt::Label.new("", blankPage) + pmLbl.setPixmap(blankPM) + pmLbl.setGeometry(40, 160, 300, 200) + pmLbl.setBackgroundMode(Qt::Widget::PaletteBase) + + @page.addWidget(blankPage, 1) + @page.raiseWidget(1) + + setCentralWidget(@mainView) + + initListView() + connect(@tree, SIGNAL("clicked(QListViewItem*)"), self, SLOT('lvClicked(QListViewItem*)')) + + @edit = nil + @currentPageObj = nil + @prefix = {"Dialogs" => "UIDialogs::dlg", "Widgets" => "UIWidgets::wid", "XML" => "UIXML::xml", + "Menus/Toolbars" => "UIMenus::menu", "Other" => "UIMisc::misc"} + end + + def initListView() + @tree.addColumn("Category", TREE_WIDTH - 21) +# tree.setMaximumWidth(treeWidth) + @mainView.setSizes([TREE_WIDTH, 375]) + @tree.setRootIsDecorated(true) + @tree.setVScrollBarMode(Qt::ScrollView::AlwaysOn) + topLevel = $listItems.keys() + topLevel.each do |item_1| + parent = Qt::ListViewItem.new(@tree, String.new(item_1)) + secondLevel = $listItems[item_1].keys() + secondLevel.each do |item_2| + child = Qt::ListViewItem.new(parent, String.new(item_2)) + $listItems[item_1][item_2].each do |item_3| + Qt::ListViewItem.new(child, String.new(item_3)) + end + end + end + end + + def lvClicked(lvItem) + if lvItem.nil? + return + end + + if $listItems.keys().include?(lvItem.text(0)) + return + end + + p = lvItem.parent() + if $listItems.keys().include?(p.text(0)) + pfx = @prefix[p.text(0)] + funcCall = pfx + lvItem.text(0).sub("KDE::","K") + "(self)" + else + pfx = @prefix[p.parent().text(0)] + funcCall = pfx + lvItem.parent().text(0).sub("KDE::","K") + "(self)" + end + eval funcCall + end + + def addPage() + @edit = nil + @currentPageObj = nil + current = @page.widget(2) + if !current.nil? + @page.removeWidget(current) + current.dispose + end + + newPage = Qt::Widget.new(@page) + newPage.setGeometry(0, 0, 375, 390) +# newPage.setBackgroundMode(QWidget.PaletteBase) + @page.addWidget(newPage, 2) + @page.raiseWidget(2) + + return newPage + end +end + +#-------------------- main ------------------------------------------------ + +appName = "UISampler" +about = KDE::AboutData.new("uisampler", appName, "0.1") +KDE::CmdLineArgs.init(ARGV, about) +app = KDE::Application.new() +mainWindow = MainWin.new(nil, "main window") +mainWindow.show +app.exec + diff --git a/korundum/rubylib/examples/xmlgui.rb b/korundum/rubylib/examples/xmlgui.rb new file mode 100755 index 00000000..8f021ccf --- /dev/null +++ b/korundum/rubylib/examples/xmlgui.rb @@ -0,0 +1,42 @@ +#!/usr/bin/env ruby + +require 'Korundum' +require 'tempfile' + +about = KDE::AboutData.new("one", "two", "three") +#KDE::CmdLineArgs.init(about) +KDE::CmdLineArgs.init(ARGV, about) +app = KDE::Application.new() + +class Receiver < Qt::Object + slots "pressed_up()", "close()", "quit()" + def initialize main, *k + super(*k) + @main = main + end + def quit + @main.close + end +end + +RAction = Struct.new :xmlgui_name, :string, :accel, :something +class RAction + def create receiver, slot, action_collection + p self.string + KDE::Action.new self.string, self.accel, receiver, slot, action_collection, self.xmlgui_name + end +end + +# { Quit, KStdAccel::Quit, "file_quit", I18N_NOOP("&Quit"), 0, "exit" }, +std_actions = { :quit => RAction.new( "file_quit", ("&Quit"), KDE::Shortcut.new(), "exit" ) } + +begin + m = KDE::MainWindow.new + @r = Receiver.new m + mActionCollection = m.actionCollection + action = std_actions[:quit].create @r, SLOT("quit()"), mActionCollection + m.createGUI Dir.pwd + "/xmlgui.rc" + app.setMainWidget(m) + m.show + app.exec() +end diff --git a/korundum/rubylib/examples/xmlgui.rc b/korundum/rubylib/examples/xmlgui.rc new file mode 100644 index 00000000..1c5d03fc --- /dev/null +++ b/korundum/rubylib/examples/xmlgui.rc @@ -0,0 +1,18 @@ +<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd"> +<kpartgui name="xmlgui" version="1"> + +<MenuBar> + + <Menu name="file" noMerge="1"><text>&File</text> + <Action name="file_open"/> + <Action name="file_save"/> + <Action name="file_save_as"/> + <Separator/> + <Action name="file_print"/> + <Separator/> + <Action name="file_quit"/> + </Menu> + +</MenuBar> + +</kpartgui> diff --git a/korundum/rubylib/examples/xmlmenudemo.rb b/korundum/rubylib/examples/xmlmenudemo.rb new file mode 100644 index 00000000..a246ac25 --- /dev/null +++ b/korundum/rubylib/examples/xmlmenudemo.rb @@ -0,0 +1,314 @@ +=begin +This is a ruby version of Jim Bublitz's pykde program, translated by Richard Dale +=end + +=begin +This template constructs an application with menus, toolbar and statusbar. +It uses KDE classes and methods that simplify the task of building and +operating a GUI. It is recommended that this approach be used, rather +than the primitive approach in menuapp1.py +=end + +=begin +Copyright 2003 Jim Bublitz + +Terms and Conditions + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files(the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +Except as contained in this notice, the name of the copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in this Software without prior written authorization from the +copyright holder. +=end + +require 'Korundum' + +class MainWin < KDE::MainWindow + + STATUSBAR_LEFT = 1 + STATUSBAR_MIDDLE = 2 + STATUSBAR_RIGHT = 3 + + slots 'slotFake()', 'slotNew()', 'slotOpen()', 'slotSave()', 'slotSaveAs()', 'slotPrint()', 'slotRadio()', + 'slotQuit()', 'slotUndo()', 'slotRedo()', 'slotCut()', 'slotCopy()', 'slotPaste()', 'slotFind()', + 'slotFindNext()', 'slotReplace()', 'slotSpecial()', 'slotToggle2()', 'slotZoomIn()', 'slotZoomOut()' + + def initialize(*args) + super + + initActions() + setGeometry(0, 0, 350, 200) + + # The second arg of createGUI needs to be 0(or false) + # to enable XMLGUI features like ActionList(in 'dynamicActions') + # If the default is used(true), the dynamic actions will not + # appear in the menus + uifilebase = Dir.getwd + '/xmlmenudemoui.rc' + createGUI(uifilebase, false) + + dynamicActions() + + # Can't do this until the toolBar has been created in createGUI + stretchlbl = Qt::Label.new("", toolBar()) + toolBar().setStretchableWidget(stretchlbl) + + initStatusBar() + + @saveAction.setEnabled(false) + @saveAsAction.setEnabled(false) + end + + def initActions() + # This is used in all of the KDE::Action/KDE::StdAction constructors -- + # Seems more efficient to only do the call once + acts = actionCollection() + + # "File" menu items + newAction = KDE::StdAction.openNew(self, SLOT('slotNew()'), acts) + openAction = KDE::StdAction.open(self, SLOT('slotOpen()'), acts) + @saveAction = KDE::StdAction.save(self, SLOT('slotSave()'), acts) + @saveAsAction = KDE::StdAction.saveAs(self, SLOT('slotSaveAs()'), acts) + printAction = KDE::StdAction.print(self, SLOT('slotPrint()'), acts) + quitAction = KDE::StdAction.quit(self, SLOT('slotQuit()'), acts) + + # "Edit" menu items + undoAction = KDE::StdAction.undo(self, SLOT('slotUndo()'), acts) + redoAction = KDE::StdAction.redo(self, SLOT('slotRedo()'), acts) + cutAction = KDE::StdAction.cut(self, SLOT('slotCut()'), acts) + copyAction = KDE::StdAction.copy(self, SLOT('slotCopy()'), acts) + pasteAction = KDE::StdAction.paste(self, SLOT('slotPaste()'), acts) + findAction = KDE::StdAction.find(self, SLOT('slotFind()'), acts) + findNextAction = KDE::StdAction.findNext(self, SLOT('slotFindNext()'), acts) + replaceAction = KDE::StdAction.replace(self, SLOT('slotReplace()'), acts) + + # NOTE!!!! You must specify a parent and name for the action object in its constructor + # Normally in a constructor like + # + # someObject(Qt::Widget *parent = 0, const char *name = 0) + # + # the parent may or may not be assigned, but widgets usually ignore the + # name argument. For an action of *any* type(other than KDE::StdAction), + # the 'name' argument is what is used to load the action into the menus + # and toolBar(in the line below, "specialActionName"). The XMLGUI mechanism + # has no way to find out about the action objects except through their + # object names - the variable the object is assigned to('specialAction') + # has no meaning in XNLGUI terms except through the objects 'name' member value + + specialAction = KDE::Action.new(i18n("Special"), KDE::Shortcut.new(0), self, SLOT('slotSpecial()'), acts, "specialActionName") + + # Demo menu items + + # KDE::ToggleAction has an isChecked member and emits the "toggle" signal + toggle1Action = KDE::ToggleAction.new("Toggle 1", KDE::Shortcut.new(0), acts, "toggle1Action") + toggle2Action = KDE::ToggleAction.new("Toggle 2", KDE::Shortcut.new(0), self, SLOT('slotToggle2()'), acts, "toggle2Action") + + # A separator - create once/use everywhere + separateAction = KDE::ActionSeparator.new(acts, "separateAction") + + # Font stuff in menus or toolbar + fontAction = KDE::FontAction.new("Font", KDE::Shortcut.new(0), acts, "fontAction") + fontSizeAction = KDE::FontSizeAction.new("Font Size", KDE::Shortcut.new(0), acts, "fontSizeAction") + + fontAction.setComboWidth(150) + fontSizeAction.setComboWidth(75) + + # Need to assign an icon to actionMenu below + icons = KDE::IconLoader.new() + iconSet = Qt::IconSet.new(icons.loadIcon("viewmag", KDE::Icon::Toolbar)) + + # Nested menus using KDE::Actions.new(also nested on toolbar) + actionMenu = KDE::ActionMenu.new("Action Menu", acts, "actionMenu") + actionMenu.setIconSet(iconSet) + + # By using KDE::StdAction here, the XMLGUI mechanism will automatically + # create a 'View' menu and insert "Zoom In" and "Zoom Out" objects + # in it. This happens because before parsing our *ui.rc file, + # the standard KDE::DE file config/ui/ui_standards.rc is parsed, and + # then our *ui.rc file is merged with the result - this gives KDE::DE + # menus and toolBars a standard "look" and item placement(including + # separators). Creating the KDE::StdActions alone is sufficient - you + # could delete their references from the *ui.rc file and the menu + # items would still be created via ui_standards.rc + actionMenu.insert(KDE::StdAction.zoomIn(self, SLOT('slotZoomIn()'), acts)) + actionMenu.insert(KDE::StdAction.zoomOut(self, SLOT('slotZoomOut()'), acts)) + + radio1Action = KDE::RadioAction.new("Radio 1", KDE::Shortcut.new(0), self, SLOT('slotRadio()'), acts, "radio1") + radio1Action.setExclusiveGroup("Radio") + radio1Action.setChecked(true) + radio2Action = KDE::RadioAction.new("Radio 2", KDE::Shortcut.new(0), self, SLOT('slotRadio()'), acts, "radio2") + radio2Action.setExclusiveGroup("Radio") + radio3Action = KDE::RadioAction.new("Radio 3", KDE::Shortcut.new(0), self, SLOT('slotRadio()'), acts, "radio3") + radio3Action.setExclusiveGroup("Radio") + end + + + def initStatusBar() + statusBar().insertItem("", STATUSBAR_LEFT, 1000, true) + statusBar().insertItem("", STATUSBAR_MIDDLE, 1000, true) + statusBar().insertItem("", STATUSBAR_RIGHT, 1000, true) + end + + def dynamicActions() + # This creates something like a 'recent files list' in the 'File' menu + # (There is a KDE::RecentFilesAction that probably should be used instead, + # but this demos the use of action lists) + # The code here corresponds to the <ActionList name="recent"/> entry + # in the rc file + + # Just fake some filenames for now + fakeFiles = ["kaction.sip", "kxmlguiclient.sip"] + + # Clear the old entries, so we don't end up accumulating entries in the menu + unplugActionList("recent"); + dynamicActionsList = [] + + # Create a KDE::Action for each entry and store the KDE::Actions in a list + # Use 'nil' for the KDE::ActionCollection argument in the KDE::Action constructor + # in this case only + (0...fakeFiles.length).each do |i| + act = KDE::Action.new(i18n(" &#{i.to_s} #{fakeFiles[i]}"), KDE::Shortcut.new(0), + self, SLOT('slotFake()'), nil, fakeFiles[i].sub(/.sip$/,'') + "open") + dynamicActionsList << act + end + + # Update the menu with the most recent KDE::Actions + plugActionList("recent", dynamicActionsList) + end + + +#-------------------- slots ----------------------------------------------- + + def slotFake() + # sender() should be called before anything else + # (including "notImpl") so the correct sender + # value is returned + sender = sender().name() + notImpl("Recent files(#{sender})") + end + + # 'id' is for toolbar button signals - ignored for menu signals + def slotNew(id = -1) + notImpl("New") + end + + def slotOpen(id = -1) + notImpl("Open") + end + + def slotSave(id = -1) + notImpl("Save") + end + + def slotSaveAs() + notImpl("Save As") + end + + def slotPrint() + notImpl("Print") + end + + def slotQuit() + notImpl("Quit") + end + + def slotUndo() + notImpl("Undo") + end + + def slotRedo() + notImpl("Redo") + end + + def slotCut(id = -1) + notImpl("Cut") + end + + def slotCopy(id = -1) + notImpl("Copy") + end + + def slotPaste(id = -1) + notImpl("Paste") + end + + def slotFind() + notImpl("Find") + end + + def slotFindNext() + notImpl("Find Next") + end + + def slotReplace() + notImpl("Replace") + end + + def slotSpecial() + notImpl("Special") + end + + def slotToggle2() + notImpl("Toggle") + end + + def slotZoomIn() + notImpl("Zoom In") + end + + def slotZoomOut() + notImpl("Zoom Out") + end + + def slotRadio() + sender = sender().name() + notImpl("Radio #{sender}") + end + + def notImpl(item = "Feature") + statusBar().changeItem("#{item} not implemented", STATUSBAR_LEFT) + KDE::MessageBox.error(self, "#{item} not implemented", "Not Implemented") + statusBar().changeItem("", STATUSBAR_LEFT) + end +end + + +#-------------------- main ------------------------------------------------ + +description = "A basic application template" +version = "1.0" + +# The appName(xmlmenudemo - first argument) is required +# if the program is to automatically locate it *ui.rc file +aboutData = KDE::AboutData.new("xmlmenudemo", "xmlmenudemo", + version, description, KDE::AboutData::License_GPL, + "(C) 2003 whoever the author is") + +aboutData.addAuthor("author1", "whatever they did", "email@somedomain") +aboutData.addAuthor("author2", "they did something else", "another@email.address") + +# mainpath = os.path.dirname(os.path.abspath(sys.argv[0])) +KDE::CmdLineArgs.init(ARGV, aboutData) + +KDE::CmdLineArgs.addCmdLineOptions([["+files", "File to open", ""]]) + +app = KDE::Application.new() +mainWindow = MainWin.new(nil, "main window") +mainWindow.show +app.exec diff --git a/korundum/rubylib/examples/xmlmenudemoui.rc b/korundum/rubylib/examples/xmlmenudemoui.rc new file mode 100644 index 00000000..58f07cf6 --- /dev/null +++ b/korundum/rubylib/examples/xmlmenudemoui.rc @@ -0,0 +1,49 @@ +<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd" ><kpartgui name="xmlmenudemo" version="1"> +<MenuBar> + <Menu name="file"><text>&File</text> + <Action name="newAction"/> + <Action name="openAction"/> + <Action name="saveAction"/> + <Action name="saveAsAction"/> + <Action name="printAction"/> + <Action name="quitAction"/> + <ActionList name="recent" /> + </Menu> + <Menu name="edit"><text>&Edit</text> + <Action name="undoAction"/> + <Action name="redoAction"/> + <Action name="cutAction"/> + <Action name="copyAction"/> + <Action name="pasteAction"/> + <Action name="findAction"/> + <Action name="findNextAction"/> + <Action name="replaceAction"/> + <Action name="specialActionName"/> + </Menu> + <Menu name="demo"><text>&Demo</text> + <Action name="toggle1Action"/> + <Action name="toggle2Action"/> + <Action name="separateAction"/> + <Action name="fontAction"/> + <Action name="fontSizeAction"/> + <Action name="separateAction"/> + <Action name="actionMenu"/> + <Action name="radio1"/> + <Action name="radio2"/> + <Action name="radio3"/> + </Menu> +</MenuBar> +<ToolBar name="mainToolBar"> + <Action name="actionMenu"/> + <Action name="separateAction"/> + <Action name="separateAction"/> + <Action name="fontAction"/> + <Action name="separateAction"/> + <Action name="fontSizeAction" comboWidth="75"/> + <Action name="radio1"/> + <Action name="radio2"/> + <Action name="radio3"/> + <Merge/> +</ToolBar> +<ActionProperties /> +</kpartgui> |