=begin
/****************************************************************************
** $Id: rubyedit2_lib.rb,v 1.1.1.2 2000/11/14 17:05:08 horie Exp $
**
** Copyright (C) 1992-1998 Troll Tech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/
=end

require "qt2"
include Qt2
if $PIXDIR.nil?
  $PIXDIR = ".//"
end

class REditWindow < QMultiLineEdit
def initialize parent, name
   catchEvent
end

def setPopup popup
   @popup = popup
end

def mousePressEvent(  event )
  if( event.button == RightButton )
	@popup.exec( QCursor::pos )
  end
end

end


class REditorWindow < QMainWindow
    NewDoc = 1
    Open = 2
    Save = 3
    Print = 4
    Close = 5
    ToggleMenuBar = 6
    ToggleToolBar = 7
    ToggleStatusBar = 8
    MARGIN = 10
    Cut = 11
    Copy = 12
    Paste = 13
    SelectAll =14
    SaveAs = 15
    About = 16
    AboutQt = 17
    StyleCDEStyle = 101
    StyleMotifStyle = 102
    StylePlatinumStyle = 103
    StyleWindowsStyle = 105
    FileOpenText = "Click this button to open a new file.\n\nYou can also select the Open command from the File menu."
    FileSaveText = "Click this button to save the file you are editing.  You will be prompted for a file name.\n\nYou can also select the Save command from the File menu.\n\nNote that implementing this function is left as an exercise for the reader.";
    FilePrintText = "Click this button to print the file you are editing.\n\nYou can also select the Print command from the File menu.";


def initialize
    super 0, "example application main window"
    @printer = QPrinter.new
    @printer.setMinMax( 1, 10 );
    @openIcon = QPixmap.new($PIXDIR + "fileopen.xpm")
    @saveIcon = QPixmap.new($PIXDIR + "filesave.xpm")
    @printIcon = QPixmap.new($PIXDIR + "fileprint.xpm")
    @copyIcon = QPixmap.new($PIXDIR + "editcopy.xpm")
    @copyCut = QPixmap.new($PIXDIR + "editcut.xpm")
    @copyPaste = QPixmap.new($PIXDIR + "editpaste.xpm")

    QApplication::setStyle(QWindowsStyle.new)

    @fileTools = QToolBar.new( self, "file operations" )

    @fileOpen = QToolButton.new( @openIcon, "Open File", "",
					    self, "load",
					    @fileTools, "open file" )

    @fileSave = QToolButton.new( @saveIcon, "Save File", "",
					      self, "save",
					      @fileTools, "save file" )

    @filePrint = QToolButton.new( @printIcon, "Print File", "",
					       self, "printIt",
					       @fileTools, "print file" )
    @fileTools.addSeparator

    @editCopy = QToolButton.new( @copyIcon, "Copy Text", "",
                                               self, "copy",
                                               @fileTools, "copy text" )
    @editCut = QToolButton.new( @copyCut, "Cut Text", "",
                                               self, "cut",
                                               @fileTools, "cut text" )
    @editPaste = QToolButton.new( @copyPaste, "Paste Text", "",
                                               self, "paste",
                                               @fileTools, "paste text" )

    @fileTools.addSeparator
    QWhatsThis::whatsThisButton( @fileTools )
    QWhatsThis::add( @fileOpen, FileOpenText)
    QWhatsThis::add( @fileSave, FileSaveText)
    QWhatsThis::add( @filePrint, FilePrintText)
    
    @file = QPopupMenu.new
#    @menuBar = self.menuBar
    menuBar.insertItem( "&File", @file )
    Qt::connect(menuBar,QSIGNAL("activated(int)"),self,"menuActivated")

#    @file.insertItem( "New", self, "newDoc", Qt::CTRL+Key_N );
    @file.insertItem("New",NewDoc,-1)
    @file.setAccel(Qt::CTRL+Key_N,NewDoc)

#    @file.insertItem( openIcon, "Open", self, SLOT(load()), CTRL+Key_O );
    @file.insertItem(@openIcon,"Open",Open,-1)
    @file.setAccel(Qt::CTRL+Key_O,Open)

#    @file.insertItemQPixmapTextId( saveIcon, "Save", this, SLOT(save()), CTRL+Key_S );
    @file.insertItem(@saveIcon,"Save",Save,-1)
    @file.setAccel(Qt::CTRL+Key_S,Save)

    @file.insertItem(@saveIcon,"Save As",SaveAs,-1)
    @file.setAccel(Qt::CTRL+Key_A,SaveAs)

    @file.insertSeparator

#    file->insertItem( printIcon, "Print", this, SLOT(print()), CTRL+Key_P );
    @file.insertItem(@printIcon,"Print",Print,-1)
    @file.setAccel(Qt::CTRL+Key_P,Print)

    @file.insertSeparator

#    file->insertItem( "Close", this, SLOT(closeDoc()), CTRL+Key_W );
    @file.insertItem("Close",Close,-1)
    @file.setAccel(Qt::CTRL+Key_W,Close)

#    file->insertItem( "Quit", qApp, SLOT(quit()), CTRL+Key_Q );

    @file.insertItem("Quit",QApplication::qApp,"quit()",Qt::CTRL+Key_Q)

    @edit = QPopupMenu.new

    menuBar.insertItem( "&Edit", @edit )
    @edit.insertItem("&Copy",Copy,-1)
    @edit.setAccel(Qt::CTRL+Key_C,Copy)

    @edit.insertItem("C&ut",Cut,-1)
    @edit.setAccel(Qt::CTRL+Key_U,Cut)

    @edit.insertItem("&Paste",Paste,-1)
    @edit.setAccel(Qt::CTRL+Key_P,Paste)

    @edit.insertSeparator
    @edit.insertItem("Select &all",SelectAll, -1)
    @edit.setAccel(Qt::CTRL+Key_A,SelectAll)


    @controls = QPopupMenu.new
    menuBar.insertItem( "&Controls", @controls )

    @mb = @controls.insertItem( "Menu bar", ToggleMenuBar,-1)
    @controls.setAccel(ToggleMenuBar,Qt::CTRL+Key_M)
    #// Now an accelerator for when the menubar is invisible!
    @a = QAccel.new(self)
    @a.connectItem( @a.insertItem( CTRL+Key_M ), self, "toggleMenuBar" )

    @tb = @controls.insertItem( "Tool bar", ToggleToolBar,-1)
    @controls.setAccel(ToggleToolBar, Qt::CTRL+Key_T)

    @sb = @controls.insertItem( "Status bar", ToggleStatusBar, -1)
print "sb = #{@sb}\n"
    @controls.setAccel(ToggleStatusBar, Qt::CTRL+Key_B)

    @styleMenu = QPopupMenu.new
    @controls.insertItem("Style...",@styleMenu,-1)

    @cde = @styleMenu.insertItem("CDE",StyleCDEStyle,-1)
    @motif = @styleMenu.insertItem("Motif",StyleMotifStyle,-1)
    @platinum = @styleMenu.insertItem("Platinum",StylePlatinumStyle,-1)
    @windows = @styleMenu.insertItem("Windows",StyleWindowsStyle,-1)

    @controls.setCheckable( true )
    @controls.setItemChecked( ToggleMenuBar, true )
    @controls.setItemChecked( ToggleToolBar, true )
    @controls.setItemChecked( ToggleStatusBar, true )

    @styleMenu.setCheckable(true)
    @styleMenu.setItemChecked( StyleCDEStyle, false )
    @styleMenu.setItemChecked( StyleMotifStyle, false )
    @styleMenu.setItemChecked( StylePlatinumStyle, false )
    @styleMenu.setItemChecked( StyleWindowsStyle, true )

    @help = QPopupMenu.new
    menuBar.insertSeparator
    menuBar.insertItem( "&Help", @help)
    @help.insertItem( "&About Editor", About)
    @help.insertItem( "About &Qt", AboutQt)

    @popup = QPopupMenu.new

    @popup.insertItem("Copy",Copy,-1)
    @popup.insertItem("Cut",Cut,-1)
    @popup.insertItem("Paste",Paste,-1)
    @popup.insertSeparator
    @popup.insertItem("Toggle menu",ToggleMenuBar)
    Qt::connect(@popup,QSIGNAL("activated(int)"),self,"menuActivated")

    @e = REditWindow.new( self, "editor" )
    @e.setPopup( @popup )
    @e.setFocus
    setCentralWidget( @e );
    self.statusBar.message( "Ready", 2000 )
end

def menuActivated id
   case id
   when NewDoc
      newDoc
   when Open
      load
   when Save
      save
   when SaveAs
      saveAs
   when Print
      printIt
   when Close
      closeDoc
   when Copy
      copy
   when Cut
      cut
   when Paste
      paste
   when SelectAll
      selectAll
   when ToggleMenuBar
      toggleMenuBar
   when ToggleToolBar
      toggleToolBar
   when ToggleStatusBar
      toggleStatusBar
   when About
      about
   when AboutQt
      aboutQt
   when StyleCDEStyle
           QApplication::setStyle(QCDEStyle.new)
    @styleMenu.setItemChecked( StyleCDEStyle, true )
    @styleMenu.setItemChecked( StyleMotifStyle, false )
    @styleMenu.setItemChecked( StylePlatinumStyle, false )
    @styleMenu.setItemChecked( StyleWindowsStyle, false )

   when StyleMotifStyle
           QApplication::setStyle(QMotifStyle.new)
     @styleMenu.setItemChecked( StyleCDEStyle, false )
    @styleMenu.setItemChecked( StyleMotifStyle, true )
    @styleMenu.setItemChecked( StylePlatinumStyle, false )
    @styleMenu.setItemChecked( StyleWindowsStyle, false )

   when StylePlatinumStyle
           QApplication::setStyle(QPlatinumStyle.new)
    @styleMenu.setItemChecked( StyleCDEStyle, false )
    @styleMenu.setItemChecked( StyleMotifStyle, false )
    @styleMenu.setItemChecked( StylePlatinumStyle, true )
    @styleMenu.setItemChecked( StyleWindowsStyle, false )

   when StyleWindowsStyle
           QApplication::setStyle(QWindowsStyle.new)
    @styleMenu.setItemChecked( StyleCDEStyle, false )
    @styleMenu.setItemChecked( StyleMotifStyle, false )
    @styleMenu.setItemChecked( StylePlatinumStyle, false )
    @styleMenu.setItemChecked( StyleWindowsStyle, true )

   end
end


def newDoc
    ed = REditorWindow.new
    ed.resize( 400, 200 )
    ed.show
end

def load
  fd = QFileDialog.new(".","*.txt",nil,"fd",true)
  fd.setMode( QFileDialog::ExistingFile )
  ql =QStringList.new
  ql.append("*.txt")
  ql.append("*.rb")
  ql.append("*.*")

  fd.setFilters(ql)
  fd.show
  fn = fd.selectedFile

    if ( !fn.isEmpty() )
        fname = fn.to_str
	loadFile( fname )
    else
	self.statusBar.message( "Loading aborted", 2000 )
    end
end


def loadFile fn
    @filename = fn
    f = File::open( @filename,"r")

    @e.setAutoUpdate( false );
    @e.clear

    while (!f.eof?)
      s = f.gets
      s.chop!
      @e.append(QString::fromLocal8Bit(s))
    end
    f.close

    @e.setAutoUpdate( true )
    @e.repaint
    setCaption( @filename )

    s =  "Loaded document #{@filename} "
    self.statusBar.message( s, 2000 )
end


def save
    if (@filename == nil )
      @filename = "NewFile"
      qfilename = QFileDialog:: getSaveFileName(@filename,"*.txt",self)
      if( !qfilename.isEmpty )
         @filename = qfilename.to_str
      end
    end
    contents = @e.text
    str = contents.local8Bit
print str.to_str
print "\n"
    f = File::open(@filename,"w+")
    f.puts str.to_str
    f.close

    s = "Save document to #{@filename} "
    self.statusBar.message(s, 2000)

end

def saveAs
    @filename = "NewFile"
    qfilename = QFileDialog:: getSaveFileName(@filename,"*.txt",self)
    if( !qfilename.isEmpty )
       @filename = qfilename.to_str
    end

    contents = @e.text
    str = contents.local8Bit
    f = File::open(@filename,"w+")
    f.puts str.to_str
    f.close
    setCaption( @filename )

    s = "Save document to #{@filename}"
    self.statusBar.message(s, 2000)

end

def printIt

    pageNo = 1

    if ( @printer.setup(self) ) 		#// printer dialog
	self.statusBar.message( "Printing..." ,4000)
	p = QPainter.new(nil)
	p.begin( @printer )			#// paint on printer
	p.setFont( @e.font )
	yPos        = 0			 	#// y position for each line
	fm = p.fontMetrics
	metrics = QPaintDeviceMetrics.new( @printer )	 #// need width/height
	                                         	#// of printer surface
	for i in 0..(@e.numLines - 1)
	    if ( MARGIN + yPos > metrics.height - MARGIN )
                pageNo = pageNo + 1
		msg = "Printing (page #{pageNo})..."
		self.statusBar.message( msg ,4000)
		@printer.newPage		#// no more room on this page
		yPos = 0			#// back to top of page
	    end
	    p.drawText( MARGIN, MARGIN + yPos,
			metrics.width, fm.lineSpacing,
			ExpandTabs || DontClip,
                        @e.textLine(i) )

	    yPos = yPos + fm.lineSpacing
	end
	p.end				#// send job to printer
	self.statusBar.message( "Printing completed", 2000 )
    else
	self.statusBar.message( "Printing aborted", 2000 )
    end

end

def closeDoc

    closeBool( true )	#// close AND DELETE!
end

def copy
   @e.copyText
end

def cut
   @e.cut
end

def paste
   @e.paste
end

def selectAll
   @e.selectAll
end

def gotoLine linNum
   @e.setCursorPosition(linNum,0)
end

def toggleMenuBar

    if ( menuBar.isVisible )
	menuBar.hide
	@controls.setItemChecked( @mb, false )
    else
	menuBar.show
	@controls.setItemChecked( @mb, true )
    end
end

def toggleToolBar

    if ( @fileTools.isVisible )
	@fileTools.hide
	@controls.setItemChecked( @tb, false )
    else
	@fileTools.show
	@controls.setItemChecked( @tb, true )
    end
end

def toggleStatusBar

    if ( self.statusBar.isVisible )
	self.statusBar.hide
	@controls.setItemChecked( @sb, false )
    else
	self.statusBar.show
	@controls.setItemChecked( @sb, true )
    end
end
def about

  QMessageBox::information( self, "About Ruby/Qt Editor",
			"This is the Simple Editor application\n" + "(C) 2000 translated to Ruby/Qt by Nobuyuki Horie\n",1)
end


def aboutQt

  QMessageBox::aboutQt( self, "About Qt" )
end

end


