;******************************************************
;   Program:          CommenntedASM
;   Author:           Peyman
;   Date:             February 23, 2008
;   Target OS:        Windows All
;   Target Compiler:  PureBasic 4.0 +
;   License:          Freeware
;
;******************************************************
Global Fichier$
Global FichierAsm$
Global Projet$=""
Global DossierCourant$=GetCurrentDirectory()

file$=ProgramParameter(0)
dir$ = GetPathPart(file$)

;{ Enumeration
Enumeration
  #Window   
  #WindowASCII
  #WindowBiosInterrupy
  #WindowOptionNoyau
  #WindowOptionMemoireVideo
  #Scintilla 
  #BarreOutils
  #Menu
  ;Fenetre Option
   #OptionText_0
  #OptionString_1
  #OptionButton_2
  #OptionButton_OK
  #OptionButton_Annuler
  ;Fenêtre mémoire Vidéo
  #WindowOptionMemoireVideoTextEditor
  ;
EndEnumeration

Enumeration
  #File
  #FichierBootsecteur
  #FichierNoyau
  #FichierRemplissage
  #FichierImageDisquette144
  
  #ScrollAreaGadgetascii
  #imagegadgetascci1
  #imagegadgetascci2
  #Webgadget
EndEnumeration

#MinWidth  = 400
  #MinHeight = 300
  #MaxWidth  = 800
  #MaxHeight = 600
;}

;{ KeyWord
Keyword.s = "aaa aad aam aas adc add and call cbw clc cld cli cmc cmp cmps cmpsb cmpsw cwd daa das dec div esc hlt idiv imul in inc int into iret ja jae jb jbe jc jcxz je jg jge jl jle jmp jna jnae jnb jnbe jnc jne jng jnge jnl jnle jno jnp jns jnz jo jp jpe jpo js jz lahf lds lea les lods lodsb lodsw loop loope loopew loopne loopnew loopnz loopnzw loopw loopz loopzw mov movs movsb movsw mul neg nop not or out pop popf push pushf rcl rcr ret retf retn rol ror sahf sal sar sbb scas scasb scasw shl shr stc std sti stos stosb stosw sub test wait xchg xlat xlatb xor bound enter ins insb insw leave outs outsb outsw popa pusha pushw arpl lar lsl sgdt sidt sldt smsw str verr verw clts lgdt lidt lldt lmsw ltr bsf bsr bt btc btr bts cdq cmpsd cwde insd iretd iretdf  iretf jecxz lfs lgs lodsd loopd  looped  loopned  loopnzd  loopzd  lss movsd movsx movzx outsd popad popfd pushad pushd  pushfd scasd seta setae setb setbe setc sete setg setge setl setle setna setnae setnb setnbe setnc setne setng setnge setnl setnle setno setnp setns setnz seto setp setpe setpo sets setz shld shrd stosd bswap cmpxchg invd  invlpg  wbinvd  xadd lock rep repe repne repnz repz cflush cpuid emms femms cmovo cmovno cmovb cmovc cmovnae cmovae cmovnb cmovnc cmove cmovz cmovne cmovnz cmovbe cmovna cmova cmovnbe cmovs cmovns cmovp cmovpe cmovnp cmovpo cmovl cmovnge cmovge cmovnl cmovle cmovng cmovg cmovnle cmpxchg486 cmpxchg8b  loadall loadall286 ibts icebp int1 int3 int01 int03 iretw popaw popfw pushaw pushfw rdmsr rdpmc rdshr rdtsc rsdc rsldt rsm rsts salc smi smint smintold svdc svldt svts syscall sysenter sysexit sysret ud0 ud1 ud2 umov xbts wrmsr wrshr"
Keyword2.s = "f2xm1 fabs fadd faddp fbld fbstp fchs fclex fcom fcomp fcompp fdecstp fdisi fdiv fdivp fdivr fdivrp feni ffree fiadd ficom ficomp fidiv fidivr fild fimul fincstp finit fist fistp fisub fisubr fld fld1 fldcw fldenv fldenvw fldl2e fldl2t fldlg2 fldln2 fldpi fldz fmul fmulp fnclex fndisi fneni fninit fnop fnsave fnsavew fnstcw fnstenv fnstenvw fnstsw fpatan fprem fptan frndint frstor frstorw fsave fsavew fscale fsqrt fst fstcw fstenv fstenvw fstp fstsw fsub fsubp fsubr fsubrp ftst fwait fxam fxch fxtract fyl2x fyl2xp1 fsetpm fcos fldenvd fnsaved fnstenvd fprem1 frstord fsaved fsin fsincos fstenvd fucom fucomp fucompp fcomi fcomip ffreep fcmovb fcmove fcmovbe fcmovu fcmovnb fcmovne fcmovnbe fcmovnu"
Keyword3.s = "ah al ax bh bl bp bx ch cl cr0 cr2 cr3 cr4 cs cx dh di dl dr0 dr1 dr2 dr3 dr6 dr7 ds dx eax ebp ebx ecx edi edx es esi esp fs gs si sp ss st tr3 tr4 tr5 tr6 tr7 st0 st1 st2 st3 st4 st5 st6 st7 mm0 mm1 mm2 mm3 mm4 mm5 mm6 mm7 xmm0 xmm1 xmm2 xmm3 xmm4 xmm5 xmm6 xmm7"
Keyword4.s = ".186 .286 .286c .286p .287 .386 .386c .386p .387 .486 .486p .8086 .8087 .alpha .break .code .const .continue .cref .data .data?  .dosseg .else .elseif .endif .endw .err .err1 .err2 .errb .errdef .errdif .errdifi .erre .erridn .erridni .errnb .errndef .errnz .exit .fardata .fardata? .if .lall .lfcond .list .listall .listif .listmacro .listmacroall  .model .no87 .nocref .nolist .nolistif .nolistmacro .radix .repeat .sall .seq .sfcond .stack .startup .tfcond .type .until .untilcxz .while .xall .xcref .xlist alias align assume catstr comm comment db dd df dosseg dq dt dup dw echo else elseif elseif1 elseif2 elseifb elseifdef elseifdif elseifdifi elseife elseifidn elseifidni elseifnb elseifndef end endif endm endp ends eq equ even exitm extern externdef extrn for forc ge goto group gt high highword if if1 if2 ifb ifdef ifdif ifdifi ife  ifidn ifidni ifnb ifndef include includelib instr invoke irp irpc label le length lengthof local low lowword lroffset lt macro mask mod .msfloat name ne offset opattr option org %out page popcontext proc proto ptr public purge pushcontext record repeat rept seg segment short size sizeof sizestr struc struct substr subtitle subttl textequ this title type typedef union while width db dw dd dq dt resb resw resd resq rest incbin equ times %define %idefine %xdefine %xidefine %undef %assign %iassign %strlen %substr %macro %imacro %endmacro %rotate .nolist %if %elif %else %endif %ifdef %ifndef %elifdef %elifndef %ifmacro %ifnmacro %elifmacro %elifnmacro %ifctk %ifnctk %elifctk %elifnctk %ifidn %ifnidn %elifidn %elifnidn %ifidni %ifnidni %elifidni %elifnidni %ifid %ifnid %elifid %elifnid %ifstr %ifnstr %elifstr %elifnstr %ifnum %ifnnum %elifnum %elifnnum %error %rep %endrep %exitrep %include %push %pop %repl struct endstruc istruc at iend align alignb %arg %stacksize %local %line bits use16 use32 section absolute extern global common cpu org section group import export"
Keyword5.s = "$ ? @b @f addr basic byte c carry? dword far far16 fortran fword near near16 overflow? parity? pascal qword  real4  real8 real10 sbyte sdword sign? stdcall sword syscall tbyte vararg word zero? flat near32 far32 abs all assumes at casemap common compact cpu dotname emulator epilogue error export expr16 expr32 farstack flat forceframe huge language large listing ljmp loadds m510 medium memory nearstack nodotname noemulator nokeyword noljmp nom510 none nonunique nooldmacros nooldstructs noreadonly noscoped nosignextend nothing notpublic oldmacros oldstructs os_dos para private prologue radix readonly req scoped setif2 smallstack tiny use16 use32 uses a16 a32 o16 o32 byte word dword nosplit $ $$ seq wrt flat large small .text .data .bss near far %0 %1 %2 %3 %4 %5 %6 %7 %8 %9"
Keyword6.s = "addpd addps addsd addss andpd andps andnpd andnps cmpeqpd cmpltpd cmplepd cmpunordpd cmpnepd cmpnltpd cmpnlepd cmpordpd cmpeqps cmpltps cmpleps cmpunordps cmpneps cmpnltps cmpnleps cmpordps cmpeqsd cmpltsd cmplesd cmpunordsd cmpnesd cmpnltsd cmpnlesd cmpordsd cmpeqss cmpltss cmpless cmpunordss cmpness cmpnltss cmpnless cmpordss comisd comiss cvtdq2pd cvtdq2ps cvtpd2dq cvtpd2pi cvtpd2ps cvtpi2pd cvtpi2ps cvtps2dq cvtps2pd cvtps2pi cvtss2sd cvtss2si cvtsd2si cvtsd2ss cvtsi2sd cvtsi2ss cvttpd2dq cvttpd2pi cvttps2dq cvttps2pi cvttsd2si cvttss2si divpd divps divsd divss fxrstor fxsave ldmxscr lfence mfence maskmovdqu maskmovdq maxpd maxps paxsd maxss minpd minps minsd minss movapd movaps movdq2q movdqa movdqu movhlps movhpd movhps movd movq movlhps movlpd movlps movmskpd movmskps movntdq movnti movntpd movntps movntq movq2dq movsd movss movupd movups mulpd mulps mulsd mulss orpd orps packssdw packsswb packuswb paddb paddsb paddw paddsw paddd paddsiw paddq paddusb paddusw pand pandn pause paveb pavgb pavgw pavgusb pdistib pextrw pcmpeqb pcmpeqw pcmpeqd pcmpgtb pcmpgtw pcmpgtd pf2id pf2iw pfacc pfadd pfcmpeq pfcmpge pfcmpgt pfmax pfmin pfmul pmachriw pmaddwd pmagw pmaxsw pmaxub pminsw pminub pmovmskb pmulhrwc pmulhriw pmulhrwa pmulhuw pmulhw pmullw pmuludq pmvzb pmvnzb pmvlzb pmvgezb pfnacc pfpnacc por prefetch prefetchw prefetchnta prefetcht0 prefetcht1 prefetcht2 pfrcp pfrcpit1 pfrcpit2 pfrsqit1 pfrsqrt pfsub pfsubr pi2fd pf2iw pinsrw psadbw pshufd pshufhw pshuflw pshufw psllw pslld psllq pslldq psraw psrad psrlw psrld psrlq psrldq psubb psubw psubd psubq psubsb psubsw psubusb psubusw psubsiw pswapd punpckhbw punpckhwd punpckhdq punpckhqdq punpcklbw punpcklwd punpckldq punpcklqdq pxor rcpps rcpss rsqrtps rsqrtss sfence shufpd shufps sqrtpd sqrtps sqrtsd sqrtss stmxcsr subpd subps subsd subss ucomisd ucomiss unpckhpd unpckhps unpcklpd unpcklps xorpd xorps"
;}

Procedure.l Scintilla(hsci.l, p1.l, p2.l=0, p3.l=0)
  ProcedureReturn ScintillaSendMessage(hsci,p1,p2,p3)
EndProcedure

ProcedureDLL ScintillaCallBack(Gadget, *scinotify.SCNotification)
  If *scinotify\nmhdr\code = #SCN_MODIFIED
    
    LenghofLines =  Len(StrU(Scintilla(#Scintilla, #SCI_GETLINECOUNT)));, #Long
    
    Scintilla(#Scintilla, #SCI_SETMARGINWIDTHN, 0, 37+(LenghofLines-3)*10)
    
    
  EndIf
  
  
EndProcedure

Procedure WindowCallback(WindowID, Message, wParam, lParam)
  ReturnValue = #PB_ProcessPureBasicEvents
  
  If Message = #WM_MOVE
    
    
  ElseIf Message = #WM_GETMINMAXINFO
    
    *pMinMax.MINMAXINFO = lParam
    *pMinMax\ptMinTrackSize\x=#MinWidth
    *pMinMax\ptMinTrackSize\y=#MinHeight
    *pMinMax\ptMaxTrackSize\x=#MaxWidth
    *pMinMax\ptMaxTrackSize\y=#MaxHeight
    ReturnValue = 0
    
    
  ElseIf Message = #WM_SIZE
    
    
    ResizeGadget(#Scintilla,0,0,WindowWidth(#Window),WindowHeight(#Window))
    
  EndIf
  
  
  ProcedureReturn  ReturnValue
  
EndProcedure

Procedure NewFile()
  FichierAsm$=""
  Scintilla(#Scintilla, #SCI_SETTEXT, 0, @"")
  If  GetMenuItemState(#Menu, 11) =1
    SetWindowTitle(0,"Nouveau - Secteur de Boot")
  Else
    SetWindowTitle(0,"Nouveau - Noyau")
    EndIf
EndProcedure

Procedure LoadFile(filename.s)
  If filename <> ""
    file.l = ReadFile(#PB_Any, filename)
    If file <> 0
      len.l = Lof(file)
      *mem = AllocateMemory(len)
      If *mem
        ReadData(file, *mem, len)
        Scintilla(#Scintilla, #SCI_SETTEXT, 0, *mem)
        FreeMemory(*mem)
      EndIf
      CloseFile(file)
    EndIf
    
    LenghofLines =  Len(StrU(Scintilla(#Scintilla, #SCI_GETLINECOUNT)));, #Long
    
    Scintilla(#Scintilla, #SCI_SETMARGINWIDTHN, 0, 37+(LenghofLines-3)*10)
    
    FichierAsm$=filename
    SetWindowTitle(#Window,GetFilePart(filename))
  EndIf
EndProcedure

Procedure SaveFileAs()
  FichierAsm$=SaveFileRequester("Sauvegarder un fichier sous", "Test.asm", "Assembleur (*.asm)|*.asm|Texte (*.txt)|*.txt|PureBasic (*.pb)|*.pb|Tous les fichiers (*.*)|*.*", 0)
  ;Debug FichierAsm$
  If FichierAsm$
    SetWindowTitle(#Window,GetFilePart(FichierAsm$))
    Fichier$=FichierAsm$
    ;StatusBarText(#StatusBar,1,SciFile)
    If CreateFile(#File, FichierAsm$)
      FileLenght = ScintillaSendMessage(#Scintilla, #SCI_GETLENGTH)+1
      *MemoryID = AllocateMemory(FileLenght)
      If *MemoryID
        ScintillaSendMessage(#Scintilla, #SCI_GETTEXT, FileLenght, *MemoryID)
        WriteData(#File, *MemoryID, FileLenght)
        FreeMemory(*MemoryID)
      EndIf
      CloseFile(#File)
    EndIf
  EndIf
EndProcedure

Procedure SaveFile(filename.s)
  If FichierAsm$<>""
    If CreateFile(#File, FichierAsm$)
      FileLenght = Scintilla(#Scintilla, #SCI_GETLENGTH, 0, 0)+1
      *MemoryID = AllocateMemory(FileLenght)
      If *MemoryID
        ScintillaSendMessage(#Scintilla, #SCI_GETTEXT, FileLenght, *MemoryID)
        WriteData(#File, *MemoryID, FileLenght)
        FreeMemory(*MemoryID)
      EndIf
      CloseFile(#File)
    EndIf
  Else
    SaveFileAs()
  EndIf
EndProcedure

Procedure OpenWindowOptionNoyau()
    
  If OpenWindow(#WindowOptionNoyau, 411, 164, 274, 142, "Options Noyau", #PB_Window_Tool|#PB_Window_TitleBar|#PB_Window_ScreenCentered|#PB_Window_SystemMenu|#PB_Window_SizeGadget)
    TextGadget(#OptionText_0, 5, 10, 255, 30, "Changer le fichier de boot par défaut :")
    StringGadget(#OptionString_1, 5, 50, 225, 30, "PureOSNoyau.bin")
    ButtonGadget(#OptionButton_2, 235, 50, 35, 30, "...")
    ButtonGadget(#OptionButton_OK, 5, 90, 130, 40, "OK")
    ButtonGadget(#OptionButton_Annuler, 140, 90, 130, 40, "Annuler")
  EndIf
EndProcedure

Procedure OpenWindowMemoireVideo()
  
  If OpenWindow(#WindowOptionMemoireVideo, 0, 0, 1020, 550, "Mémoire Vidéo", #PB_Window_Tool|#PB_Window_TitleBar|#PB_Window_ScreenCentered|#PB_Window_SystemMenu|#PB_Window_SizeGadget)
    EditorGadget(#WindowOptionMemoireVideoTextEditor, 3, 3, 1020-6, 550-6 , #PB_Editor_ReadOnly)
    Font1 = LoadFont(#PB_Any, "Courier",  8)
    SetGadgetFont(#WindowOptionMemoireVideoTextEditor, FontID(Font1)) 
    
    mem=753664 ; $B8000
       
    k=0
    For page=0 To 3 ; 4 pages
      Texte$="   "
      AddGadgetItem(#WindowOptionMemoireVideoTextEditor, -1, "")
      AddGadgetItem(#WindowOptionMemoireVideoTextEditor, -1, "")
      AddGadgetItem(#WindowOptionMemoireVideoTextEditor, -1, "Page " + Str(page))
        
      ;ligne 1 n° de colonne
      For i=0 To 79
        Texte$ + RSet(Str(i), 5, "0") + " "
      Next i
      AddGadgetItem(#WindowOptionMemoireVideoTextEditor, -1, Texte$)
            
      Texte$=""
      For j=0 To 24
        Texte$=RSet(Str(j), 2, "0") + " "
        For i=0 To 79
          Texte$ + Hex(mem+k, #PB_Long) + " " 
          k + 2 
        Next i
        AddGadgetItem(#WindowOptionMemoireVideoTextEditor, -1, Texte$)
        Texte$=""
      Next j
           
    Next page

  EndIf 
  EndProcedure
  

UsePNGImageDecoder()

OpenWindow(#Window, 50, 10, 800, 750, "PureOS : Secteur de Boot", #PB_Window_SizeGadget|#PB_Window_SystemMenu|#PB_Window_MinimizeGadget|#PB_Window_MaximizeGadget)


;{-ToolBar
If CreateToolBar(#BarreOutils, WindowID(0)) ;  La ToolBar est attachée à la fenêtre
  ToolBarStandardButton(0, #PB_ToolBarIcon_New)
  ToolBarStandardButton(1, #PB_ToolBarIcon_Open)
  ToolBarStandardButton(2, #PB_ToolBarIcon_Save)
  
  ToolBarSeparator()
  
  CreateImage(3,16,16)
  StartDrawing(ImageOutput(3))
  DrawingMode(#PB_2DDrawing_Transparent)
  Box(0, 0, 16,16,$D2F4FC)
  x=16/2-TextWidth("F")/2
  y=16/2-TextHeight("F")/2
  DrawText(x,y, "F", RGB(211,211,211))
  StopDrawing()
  ToolBarImageButton(3, ImageID(3))
  ToolBarToolTip(#BarreOutils, 3, "F3 -> Compiler avec FASM")
  
  CreateImage(4,16,16)
  StartDrawing(ImageOutput(4))
  DrawingMode(#PB_2DDrawing_Transparent)
  Box(0, 0, 16,16,$D2F4FC)
  x=16/2-TextWidth("N")/2
  y=16/2-TextHeight("N")/2
  DrawText(x,y, "N", RGB(211,211,211))
  StopDrawing()
  ToolBarImageButton(4, ImageID(4))
  ToolBarToolTip(#BarreOutils, 4, "F4 -> Compiler avec NASM")
  
  ToolBarSeparator()
  
  CreateImage(5,16,16)
  StartDrawing(ImageOutput(5))
  DrawingMode(#PB_2DDrawing_Transparent)
  Box(0, 0, 16,16,$00FF00)
  x=16/2-TextWidth("F")/2
  y=16/2-TextHeight("F")/2
  DrawText(x,y, "F", RGB(255,0,0))
  StopDrawing()
  ToolBarImageButton(5,ImageID(5))
  ToolBarToolTip(#BarreOutils, 5, "F5 -> Compiler avec FASM + QEMU")
  
  CreateImage(6,16,16)
  StartDrawing(ImageOutput(6))
  DrawingMode(#PB_2DDrawing_Transparent)
  Box(0, 0, 16,16,$00FF00)
  x=16/2-TextWidth("N")/2
  y=16/2-TextHeight("N")/2
  DrawText(x,y, "N", RGB(255,0,0))
  StopDrawing()
  ToolBarImageButton(6,ImageID(6))
  ToolBarToolTip(#BarreOutils, 6, "F6 -> Compiler avec NASM + QEMU")
  
  
  ToolBarSeparator()
  
  CreateImage(7,16,16)
  StartDrawing(ImageOutput(7))
  DrawingMode(#PB_2DDrawing_Transparent)
  Box(0, 0, 16,16,$0779F8)
  x=16/2-TextWidth("F")/2
  y=16/2-TextHeight("F")/2
  DrawText(x,y, "F", RGB(255,255,255))
  StopDrawing()
  ToolBarImageButton(7,ImageID(7))
  ToolBarToolTip(#BarreOutils, 7, "F7 -> Compiler avec FASM + BOSCH")
  
  CreateImage(8,16,16)
  StartDrawing(ImageOutput(8))
  DrawingMode(#PB_2DDrawing_Transparent)
  Box(0, 0, 16,16,$0779F8)
  x=16/2-TextWidth("N")/2
  y=16/2-TextHeight("N")/2
  DrawText(x,y, "N", RGB(255,255,255))
  StopDrawing()
  ToolBarImageButton(8,ImageID(8))
  ToolBarToolTip(#BarreOutils, 8, "F8 -> Compiler avec NASM + BOSCH")
  
  ;   #PB_ToolBarIcon_Cut          (Couper)
  ;   #PB_ToolBarIcon_Copy         (Copier)
  ;   #PB_ToolBarIcon_Paste        (Coller)
  ;   #PB_ToolBarIcon_Undo         (Annule l'action)
  ;   #PB_ToolBarIcon_Redo  
  
  
EndIf
;}

;{-Menu
;If CreateMenu(#Menu, WindowID(#Window))
;If LoadImage(0, OpenFileRequester("Choisissez une icone", "", "", 0))

If CreateImageMenu(#Menu, WindowID(#Window),#PB_Menu_ModernLook)
  ;(raccourcis : 
  MenuTitle("&Projet")
  
;   OpenSubMenu("&Nouveau"+Chr(9)+"Ctrl+N")       ; Crée un sous-menu
;   MenuItem( 11, "Secteur de Boot")
;   MenuItem( 12, "Noyau (Kernel)")
  ;CloseSubMenu()  
  MenuItem(0, "Nouveau"+Chr(9)+"Ctrl+N")
  MenuItem(1, "&Ouvrir"+Chr(9)+"Ctrl+O");, ImageID(0))
  MenuItem(2, "&Sauver"+Chr(9)+"Ctrl+S")
  MenuItem(99, "&Enregistrer sous..."+Chr(9)+"Ctrl+E")
  MenuBar()
  MenuItem(100, "&Quitter"+Chr(9)+"Ctrl+Q")
  
  MenuTitle("&Compiler")
  MenuItem(3, "Compiler avec &FASM"+Chr(9)+"F3")
  MenuItem(4, "Compiler avec &NASM"+Chr(9)+"F4");
  MenuBar()
  MenuItem(5, "Compiler avec &FASM et Lancer QEMU"+Chr(9)+"F5")
  MenuItem(6, "Compiler avec &NASM et Lancer QEMU"+Chr(9)+"F6")
  MenuBar()
  MenuItem(7, "Compiler avec &FASM et Lancer BOSCH"+Chr(9)+"F7")
  MenuItem(8, "Compiler avec &NASM et Lancer BOSCH"+Chr(9)+"F8")
  
  MenuTitle("&Outils")
  MenuItem(9, "Table ASCII")
  MenuItem(10, "Bios Interruptions")
  MenuBar()
  MenuItem(14, "Mémoire Vidéo")
  
  MenuTitle("Op&tions")
  MenuItem(13, "Définir Secteur de Boot par défaut")
   MenuBar()
  MenuItem(11, "Secteur de Boot")
  MenuItem(12, "Noyau (Kernel)")
  SetMenuItemState(#Menu, 11, 1) ; Checked

  
  ;   
EndIf

;}

;{ Scintilla 
InitScintillaStaticFull()
;SetWindowCallback(@WindowCallback())


;GetClientRect_(WindowID(#Window), rect.RECT)

;ScintillaGadget(#Scintilla, 0, MenuHeight() +ToolBarHeight(#BarreOutils), rect\right, rect\bottom, @ScintillaCallBack())
;ScintillaGadget(#Scintilla, 0, MenuHeight()+ToolBarHeight(#BarreOutils), WindowWidth(#Window), WindowHeight(#Window), @ScintillaCallBack())
ScintillaGadget(#Scintilla, 0, 28, WindowWidth(#Window), WindowHeight(#Window), @ScintillaCallBack())

; Debug MenuHeight()
; Debug ToolBarHeight(#BarreOutils)


; Delete Tab Key For Tab in Scintilla
RemoveKeyboardShortcut(#Window, #PB_Shortcut_Tab)
RemoveKeyboardShortcut(#Window, #PB_Shortcut_Tab | #PB_Shortcut_Shift)

; Other
Scintilla(#Scintilla, #SCI_SETINDENT, 2)


; Font And Size
Scintilla(#Scintilla, #SCI_STYLESETFONT, #STYLE_DEFAULT, @"Courier New")
Scintilla(#Scintilla, #SCI_STYLESETSIZE, #STYLE_DEFAULT, 10)
Scintilla(#Scintilla, #SCI_SETMARGINTYPEN, 0, #SC_MARGIN_NUMBER)
Scintilla(#Scintilla, #SCI_SETMARGINWIDTHN, 0, 50)
Scintilla(#Scintilla, #SCI_SETMARGINTYPEN, 0, #SC_MARGIN_NUMBER)
Scintilla(#Scintilla, #SCI_SETMARGINMASKN, 2, #SC_MASK_FOLDERS)
Scintilla(#Scintilla, #SCI_SETMARGINWIDTHN, 0, 37)
Scintilla(#Scintilla, #SCI_SETMARGINWIDTHN, 1, 1)
Scintilla(#Scintilla, #SCI_SETMARGINWIDTHN, 2, 18)
Scintilla(#Scintilla, #SCI_SETMARGINSENSITIVEN, 2, #True)

; Choose folding icons
Scintilla(#Scintilla, #SCI_MARKERDEFINE, #SC_MARKNUM_FOLDEROPEN, #SC_MARK_BOXMINUS)
Scintilla(#Scintilla, #SCI_MARKERDEFINE, #SC_MARKNUM_FOLDER, #SC_MARK_BOXPLUS)
Scintilla(#Scintilla, #SCI_MARKERDEFINE, #SC_MARKNUM_FOLDERSUB, #SC_MARK_VLINE)
Scintilla(#Scintilla, #SCI_MARKERDEFINE, #SC_MARKNUM_FOLDERTAIL, #SC_MARK_LCORNER)
Scintilla(#Scintilla, #SCI_MARKERDEFINE, #SC_MARKNUM_FOLDEREND, #SC_MARK_BOXPLUSCONNECTED)
Scintilla(#Scintilla, #SCI_MARKERDEFINE, #SC_MARKNUM_FOLDEROPENMID, #SC_MARK_BOXMINUSCONNECTED)
Scintilla(#Scintilla, #SCI_MARKERDEFINE, #SC_MARKNUM_FOLDERMIDTAIL, #SC_MARK_TCORNER)


; Choose folding icon colours
Scintilla(#Scintilla, #SCI_MARKERSETFORE, #SC_MARKNUM_FOLDEROPEN, RGB(236, 233, 216))
Scintilla(#Scintilla, #SCI_MARKERSETBACK, #SC_MARKNUM_FOLDEROPEN, RGB(128, 128, 128))
Scintilla(#Scintilla, #SCI_MARKERSETFORE, #SC_MARKNUM_FOLDER, RGB(236, 233, 216))
Scintilla(#Scintilla, #SCI_MARKERSETBACK, #SC_MARKNUM_FOLDER, RGB(128, 128, 128))
Scintilla(#Scintilla, #SCI_MARKERSETBACK, #SC_MARKNUM_FOLDERSUB, RGB(128, 128, 128))
Scintilla(#Scintilla, #SCI_MARKERSETBACK, #SC_MARKNUM_FOLDERTAIL, RGB(128, 128, 128))
Scintilla(#Scintilla, #SCI_MARKERSETFORE, #SC_MARKNUM_FOLDEREND, RGB(236, 233, 216))
Scintilla(#Scintilla, #SCI_MARKERSETBACK, #SC_MARKNUM_FOLDEREND, RGB(128, 128, 128))
Scintilla(#Scintilla, #SCI_MARKERSETFORE, #SC_MARKNUM_FOLDEROPENMID, RGB(236, 233, 216))
Scintilla(#Scintilla, #SCI_MARKERSETBACK, #SC_MARKNUM_FOLDEROPENMID, RGB(128, 128, 128))
Scintilla(#Scintilla, #SCI_MARKERSETBACK, #SC_MARKNUM_FOLDERMIDTAIL, RGB(128, 128, 128))

;lex setup
Scintilla(#Scintilla, #SCI_SETLEXER, #SCLEX_ASM, 0)
Scintilla(#Scintilla, #SCI_SETSTYLEBITS, 5, 0)
Scintilla(#Scintilla,#SCI_STYLESETFORE, #STYLE_DEFAULT, RGB(0,0,0));
Scintilla(#Scintilla,#SCI_STYLESETBACK, #STYLE_DEFAULT, RGB(255,255,255));
Scintilla(#Scintilla,#SCI_STYLECLEARALL);

; Set caret line colour
Scintilla(#Scintilla, #SCI_SETCARETLINEBACK, 16771304)
Scintilla(#Scintilla, #SCI_SETCARETLINEVISIBLE, #True)



; Set styles for custom lexer
Scintilla(#Scintilla, #SCI_STYLESETFORE, #SCE_ASM_DEFAULT, 0)
Scintilla(#Scintilla, #SCI_STYLESETFORE, #SCE_ASM_COMMENT, 32768)
Scintilla(#Scintilla, #SCI_STYLESETFONT, #SCE_ASM_COMMENT, @"Courier New")
Scintilla(#Scintilla, #SCI_STYLESETSIZE, #SCE_ASM_COMMENT, 9)
Scintilla(#Scintilla, #SCI_STYLESETFORE, #SCE_ASM_NUMBER, 33023)
Scintilla(#Scintilla, #SCI_STYLESETFORE, #SCE_ASM_STRING, 8421504)
Scintilla(#Scintilla, #SCI_STYLESETFORE, #SCE_ASM_OPERATOR, 8388608)
Scintilla(#Scintilla, #SCI_STYLESETBOLD, #SCE_ASM_OPERATOR, #True)
Scintilla(#Scintilla, #SCI_STYLESETFORE, #SCE_ASM_IDENTIFIER, 0)
Scintilla(#Scintilla, #SCI_STYLESETFORE, #SCE_ASM_CPUINSTRUCTION, 16711680)
Scintilla(#Scintilla, #SCI_STYLESETBOLD, #SCE_ASM_CPUINSTRUCTION, #True)
Scintilla(#Scintilla, #SCI_STYLESETFORE, #SCE_ASM_MATHINSTRUCTION, 12615680)
Scintilla(#Scintilla, #SCI_STYLESETBOLD, #SCE_ASM_MATHINSTRUCTION, #True)
Scintilla(#Scintilla, #SCI_STYLESETFORE, #SCE_ASM_REGISTER, 16744576)
Scintilla(#Scintilla, #SCI_STYLESETBACK, #SCE_ASM_REGISTER, 13434879)
Scintilla(#Scintilla, #SCI_STYLESETBOLD, #SCE_ASM_REGISTER, #True)
Scintilla(#Scintilla, #SCI_STYLESETFORE, #SCE_ASM_DIRECTIVE, 16744448)
Scintilla(#Scintilla, #SCI_STYLESETFORE, #SCE_ASM_DIRECTIVEOPERAND, 8388608)
Scintilla(#Scintilla, #SCI_STYLESETBOLD, #SCE_ASM_DIRECTIVEOPERAND, #True)
Scintilla(#Scintilla, #SCI_STYLESETFORE, #SCE_ASM_COMMENTBLOCK, 32768)
Scintilla(#Scintilla, #SCI_STYLESETFONT, #SCE_ASM_COMMENTBLOCK, @"Comic Sans MS")
Scintilla(#Scintilla, #SCI_STYLESETSIZE, #SCE_ASM_COMMENTBLOCK, 8)
Scintilla(#Scintilla, #SCI_STYLESETFORE, #SCE_ASM_CHARACTER, 32896)
Scintilla(#Scintilla, #SCI_STYLESETFORE, #SCE_ASM_STRINGEOL, 8421504)
Scintilla(#Scintilla, #SCI_STYLESETFORE, #SCE_ASM_EXTINSTRUCTION, 16512)
Scintilla(#Scintilla, #SCI_STYLESETBOLD, #SCE_ASM_EXTINSTRUCTION, #True)


; Color Of Selection
Scintilla(#Scintilla, #SCI_SETSELBACK, #True, RGB(49, 106, 197))
Scintilla(#Scintilla, #SCI_SETSELFORE, #True, RGB(255, 255, 255))


; Code Wraper
;Scintilla(#Scintilla, #SCI_SETWRAPMODE, #SC_WRAP_WORD, 0)
;Scintilla(#Scintilla, #SCI_SETWRAPVISUALFLAGS, #SC_WRAPVISUALFLAG_START | #SC_WRAPVISUALFLAG_END, 0)


; Keyword
Scintilla(#Scintilla, #SCI_SETKEYWORDS, 0, @Keyword)  ; Set KeyWord 1
Scintilla(#Scintilla, #SCI_SETKEYWORDS, 1, @Keyword2) ; Set KeyWord 2
Scintilla(#Scintilla, #SCI_SETKEYWORDS, 2, @Keyword3) ; Set KeyWord 3
Scintilla(#Scintilla, #SCI_SETKEYWORDS, 3, @Keyword4) ; Set KeyWord 4
Scintilla(#Scintilla, #SCI_SETKEYWORDS, 4, @Keyword5) ; Set KeyWord 5
Scintilla(#Scintilla, #SCI_SETKEYWORDS, 5, @Keyword6) ; Set KeyWord 6


SetFocus_(GadgetID(#Scintilla))
;}



; If file$ And FileSize(file$)>0
;   Compiler = RunProgram(#PB_Compiler_Home+"\Compilers\pbcompiler", Chr(34)+file$+Chr(34)+" /commented", dir$, #PB_Program_Hide|#PB_Program_Wait)
;   If Compiler
;     dir$+"PureBasic.asm"
;     LoadFile(dir$)
;   EndIf
; EndIf
Procedure todo()
  MessageRequester("Info", "A faire...")
EndProcedure

Repeat
  Event = WaitWindowEvent(10)
  
  Select Event
    Case #PB_Event_SizeWindow 
      ResizeGadget(#Scintilla,#PB_Ignore, #PB_Ignore,WindowWidth(#Window),WindowHeight(#Window)-MenuHeight() -ToolBarHeight(#BarreOutils))
      ;{-Event Menu 
    Case #PB_Event_Menu ; A la fois pour les menus et la barre d'outils
      ;MessageRequester("Information", "ToolBar ou Menu ID: "+Str(EventMenu()), 0)
      Select EventMenu()
        Case 0 ; Page Blanche Nouveau 
          NewFile()
        Case 1 ; Ouvrir
          ;{ openfilerequester
          ;=GetPathPart(ProgramFilename())
          FichierParDefaut$ = GetCurrentDirectory() + ""   ; Répertoire et fichier par défaut qui seront affichés
          Filtre$ = "Assembleur (*.asm)|*.asm|Texte (*.txt)|*.txt|PureBasic (*.pb)|*.pb|Tous les fichiers (*.*)|*.*"
          Filtre  = 0    ; utiliser  par défaut le premier des trois filtres possibles
          Fichier$ = OpenFileRequester("Choisissez un fichier à charger", FichierParDefaut$, Filtre$, Filtre)
          If Fichier$
            LoadFile(Fichier$)
            ;MessageRequester("Information", "Vous avez choisi le fichier suivant :"+Chr(10)+Fichier$, 0)
          Else
            ;MessageRequester("Information", "La sélection a été annulée.", 0)
          EndIf 
          ;}
          ;           
        Case 2 ;Enregistrer
          SaveFile(FichierAsm$)
          ;{ Todo  
        Case 3 : todo()
        Case 4 : todo()
        Case 5 : todo()
          ;}
        Case 3,4,5
          todo()
          
        Case 6 ; NASM + QEMU
          If Fichier$ <>"" ; ne rien faire si aucun fichier .asm n'a été chargé ou créé
            SaveFile(Fichier$)
            If projet$="" Or projet$="boot"
              ;Compilation du secteur de boot = 512 octets
              Parametre$=" -f bin -o PureOSBoot.bin " + Fichier$
              ;FichierBin$="PureOSBoot.bin"
              ;ok=DeleteFile(DossierCourant$ + "NASM\PureOSBoot.bin")
              ;Debug ok
              Debug DossierCourant$ + "NASM\PureOSBoot.bin"
              If RunProgram(GetCurrentDirectory()+"NASM\nasm.exe", parametre$, GetCurrentDirectory()+"NASM\", #PB_Program_Wait|#PB_Program_Hide )
                ; Attendre que le fichier apparaisse
                For i=1 To 5
                  If ExamineDirectory(0,GetCurrentDirectory()+"NASM\","*.bin")
                    While NextDirectoryEntry(0)
                      If DirectoryEntryType(0) = #PB_DirectoryEntry_File
                        
                        If DirectoryEntryName(0) = "PureOSBoot.bin"
                          ;Debug "ok PureOSBoot.bin"
                          FinishDirectory(0)
                          Break 2
                        EndIf
                      EndIf
                      
                    Wend
                    FinishDirectory(0)
                  EndIf
                  
                Next i
              Else 
                MessageRequester("Alerte", "La compilation avec NASM a échoué !")
              EndIf
              
            ElseIf projet$="noyau"
              ;Debug projet$
              parametre$=" -f bin -o PureOSNoyau.bin " + Fichier$
              ;FichierBin$="PureOSNoyau.bin"
              
              If RunProgram(GetCurrentDirectory()+"NASM\nasm.exe", parametre$, GetCurrentDirectory()+"NASM\", #PB_Program_Wait|#PB_Program_Hide );
                ; Attendre que le fichier apparaisse
                For i=1 To 5
                  If ExamineDirectory(0,GetCurrentDirectory()+"NASM\","*.bin")
                    While NextDirectoryEntry(0)
                      If DirectoryEntryType(0) = #PB_DirectoryEntry_File
                        
                        If DirectoryEntryName(0) = "PureOSNoyau.bin"
                          ;Debug "ok PureOSBoot.bin"
                          FinishDirectory(0)
                          Break 2
                        EndIf
                      EndIf
                      
                    Wend
                    FinishDirectory(0)
                  EndIf
                  
                Next i
              Else 
                MessageRequester("Alerte", "La compilation avec NASM a échoué !")
              EndIf
            EndIf
            
            
            ; Disquette 1.44Mo = 1440Ko*1024=1 474 560 octets = 2880 secteurs de 512 octets
            ; Secteur de boot : Il faut remplir avec n=1440*1024-512
            If CreateFile(#FichierImageDisquette144, DossierCourant$ + "PureOsBootFloppy144.bin" )
              ;Debug "ok createfile"
              ; Transfert du PureOSBoot.bin dans la disquette = PureOsBootFloppy144.bin
              If  ReadFile(#FichierBootsecteur, GetCurrentDirectory()+"NASM\"+"PureOSBoot.bin") 
                ;Debug "ok readfile"
                For i=1 To 512
                  Valeur.b = ReadByte(#FichierBootsecteur) 
                  WriteByte(#FichierImageDisquette144, Valeur)
                Next i
                erreur=0
              Else
                               MessageRequester("Alerte", "PureOSBoot.bin absent")
                               ;CloseFile(#FichierBootsecteur)
                               erreur=1
                ;End
              EndIf
              
              ; Si boot alors remplissage de la disquette avec des 0
              If Projet$="" Or Projet$="boot"
                n=1440*1024-512 
                For i=1 To n
                  WriteByte(#FichierImageDisquette144, 0)
                Next i
                If erreur =0
                  CloseFile(#FichierBootsecteur)
                  EndIf
              EndIf
              
              ; Si noyau remplissage avec le noyau
              If Projet$="noyau" 
                n=1440*1024-512 - FileSize(DossierCourant$ +"NASM\"+"PureOSNoyau.bin")
                Debug FileSize(DossierCourant$ +"NASM\"+"PureOSNoyau.bin")
                Debug n
                If n<0
                  MessageRequester("Alerte", "Noyeau trop gros pour une disquette 1.44Mo")
                  End
                EndIf
                If  ReadFile(#FichierNoyau, GetCurrentDirectory()+"NASM\"+"PureOSNoyau.bin") 
                  ;Debug "ok readfile"
                  For i=1 To FileSize(DossierCourant$ +"NASM\"+"PureOSNoyau.bin")
                    Valeur.b = ReadByte(#FichierNoyau) 
                    WriteByte(#FichierImageDisquette144, Valeur)
                  Next i
                  If n>=0
                    For i=1 To n
                      WriteByte(#FichierImageDisquette144, 0)
                    Next i
                  EndIf
                EndIf
                CloseFile(#FichierNoyau)
              EndIf
              
              
                  ;  WriteAsciiCharacter(#Fichier, Valeur) 
                Else
                  MessageRequester("Alerte", "Impossible de créer PureOsBootFloppy144.bin") 
                EndIf
                
                CloseFile(#FichierImageDisquette144)
                
                ; Attendre que le fichier apparaisse
                For i=1 To 5
                  If ExamineDirectory(0, DossierCourant$ + "NASM\","*.bin")
                    While NextDirectoryEntry(0)
                      If DirectoryEntryType(0) = #PB_DirectoryEntry_File
                        
                        If DirectoryEntryName(0) = "PureOsBootFloppy144.bin"
                          ;Debug "ok PureOsBootFloppy144.bin"
                          FinishDirectory(0)
                          Break 2
                        EndIf
                      EndIf
                      
                    Wend
                    FinishDirectory(0)
                  EndIf
                  
                Next i
                
                ; QEMU
                parametre$=" -L . -m 128 -fda ..\PureOsBootFloppy144.bin"; + ""
                If RunProgram(GetCurrentDirectory()+"QEMU\qemu.exe", parametre$, GetCurrentDirectory()+"QEMU\", #PB_Program_Wait )
                  ;Debug "ok qemu"
                Else
                  MessageRequester("Alerte", "Problème avec QEMU")
                  End
                 
            EndIf ;CreateFile "PureOsBootFloppy144.bin"
            EndIf
            Case 7 
              todo()
            Case 8 
              todo()
              
            Case 9    ;Fenêtre TABLE ASCII
              ;Debug "ok"
              If  OpenWindow(#WindowASCII, 0, 0, 1024, 620, "Table ASCII",  #PB_Window_SystemMenu| #PB_Window_MinimizeGadget,WindowID(#Window));|#PB_Window_Tool
                If ScrollAreaGadget(#ScrollAreaGadgetascii, 0, 0, 1024, 620, 1070, 600,  30 ,#PB_ScrollArea_BorderLess) 
                  
                  If LoadImage(0, GetCurrentDirectory()+"ASCII\ASCII1.PNG");560x600
                    ImageGadget(#imagegadgetascci1,  0, 0, 0, 0, ImageID(0))  
                  EndIf
                  If LoadImage(1, GetCurrentDirectory()+"ASCII\ASCII2.PNG");505x600
                    ImageGadget(#imagegadgetascci2,  560, 0, 0, 0, ImageID(1))  
                  EndIf
                EndIf   
              EndIf
              
            Case 10 ;Fenêtre INTERRUPTIONS DU BIOS
              ;Debug "ok"
              If  OpenWindow(#WindowBiosInterrupy, 0, 0, 1024, 620, "INTERRUPTIONS DU BIOS",  #PB_Window_SystemMenu| #PB_Window_MinimizeGadget,WindowID(#Window));|#PB_Window_Tool
                WebGadget(#Webgadget, 0, 0, 1020, 620, GetCurrentDirectory()+"BIOS\index.html")
              EndIf
              
            Case 11 ; Le projet secteur de boot
              SetMenuItemState(#Menu, 11, 1) ; Checked
              SetMenuItemState(#Menu, 12, 0)
              SetWindowTitle(#Window,"PureOS : Secteur de Boot")
              Projet$="boot"
              
            Case 12 ; Le projet Noyau
              SetMenuItemState(#Menu, 11, 0) ; unChecked
              SetMenuItemState(#Menu, 12, 1) ; Checked
              SetWindowTitle(#Window,"PureOS : Noyau")
              Projet$="noyau"
              
            Case 13 ; Option secteur de boot par défaut
              OpenWindowOptionNoyau()
              
            Case 14 ; Option secteur de boot par défaut
              OpenWindowMemoireVideo()
              
            Case 99 ;Enregistrer sous
              SaveFileAs()
              
            Case 100 ; Quitter
              Quit = 1
              
          EndSelect
          ;}
          
       ;TODO / A FAIRE   
       Case #PB_Event_Gadget
      EventGadget = EventGadget()
      EventType = EventType()
      If EventGadget = #OptionButton_2
        ;NomFichier$ = OpenFileRequester(Titre$, FichierParDefaut$, Filtre$, FiltrePosition [, Options])
        ElseIf EventGadget = #OptionButton_OK 
          CloseWindow(#WindowOptionNoyau)
      ElseIf EventGadget = #OptionButton_Annuler
        CloseWindow(#WindowOptionNoyau)
      EndIf   
          
        Case #PB_Event_CloseWindow  
          Select EventWindow()
            Case #Window : Quit = 1
            Case #WindowASCII
              ;DisableWindow(0,0)
              CloseWindow(#WindowASCII)
            Case #WindowBiosInterrupy
              ;DisableWindow(0,0)
              CloseWindow(#WindowBiosInterrupy)
            Case #WindowOptionNoyau
              CloseWindow(#WindowOptionNoyau)
            Case #WindowOptionMemoireVideo
              CloseWindow(#WindowOptionMemoireVideo)
          EndSelect
          
          
      EndSelect
      
    Until Quit = 1
    
    
    
    End
    
    
; ;{- Enumerations / DataSections
; ;{ Windows
; Enumeration
;   
; EndEnumeration
; ;}
; ;{ Gadgets
; Enumeration
;  
; EndEnumeration
; ;}
; Define.l Event, EventWindow, EventGadget, EventType, EventMenu
; ;}
; 
; 
; 
; 
; ;{- Event loop
; Repeat
;   Event = WaitWindowEvent()
;   Select Event
;     ; ///////////////////
;     Case #PB_Event_Gadget
;       EventGadget = EventGadget()
;       EventType = EventType()
;       If EventGadget = #Text_0
;       ElseIf EventGadget = #OptionString_1
;       ElseIf EventGadget = #OptionButton_2
;       ElseIf EventGadget = #OptionButton_OK
;       ElseIf EventGadget = #OptionButton_Annuler
;       EndIf
;     ; ////////////////////////
;     Case #PB_Event_CloseWindow
;       EventWindow = EventWindow()
;       If EventWindow = #WindowOptionNoyau
;         CloseWindow(#WindowOptionNoyau)
;         Break
;       EndIf
;   EndSelect
; ForEver
; ;
; ;}



    
    
    
    
    
    
    
    
    
    
    
    
; IDE Options = PureBasic 4.61 (Windows - x86)
; CursorPosition = 228
; FirstLine = 84
; Folding = BQc-
; EnableXP
; Executable = ..\gadget\scintilla\asm.exe
; CompileSourceDirectory