FlatCAMApp.py 259 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. import sys
  9. import traceback
  10. import urllib.request, urllib.parse, urllib.error
  11. import getopt
  12. import os
  13. import random
  14. import logging
  15. import simplejson as json
  16. import re
  17. import os
  18. from stat import S_IREAD, S_IRGRP, S_IROTH
  19. import subprocess
  20. import tkinter as tk
  21. from PyQt5 import QtCore, QtGui, QtWidgets, QtPrintSupport
  22. import time # Just used for debugging. Double check before removing.
  23. import urllib.request, urllib.parse, urllib.error
  24. import webbrowser
  25. from contextlib import contextmanager
  26. from xml.dom.minidom import parseString as parse_xml_string
  27. from copy import copy,deepcopy
  28. import numpy as np
  29. from datetime import datetime
  30. import gc
  31. ########################################
  32. ## Imports part of FlatCAM ##
  33. ########################################
  34. from ObjectCollection import *
  35. from FlatCAMObj import *
  36. from PlotCanvas import *
  37. from FlatCAMGUI import *
  38. from FlatCAMCommon import LoudDict
  39. from FlatCAMPostProc import load_postprocessors
  40. from FlatCAMEditor import FlatCAMGeoEditor, FlatCAMExcEditor
  41. from FlatCAMProcess import *
  42. from FlatCAMWorkerStack import WorkerStack
  43. from VisPyVisuals import Color
  44. from vispy.gloo.util import _screenshot
  45. from vispy.io import write_png
  46. from flatcamTools import *
  47. from multiprocessing import Pool
  48. import tclCommands
  49. # from ParseFont import *
  50. ########################################
  51. ## App ##
  52. ########################################
  53. class App(QtCore.QObject):
  54. """
  55. The main application class. The constructor starts the GUI.
  56. """
  57. # Get Cmd Line Options
  58. cmd_line_shellfile = ''
  59. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  60. try:
  61. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  62. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  63. except getopt.GetoptError:
  64. print(cmd_line_help)
  65. sys.exit(2)
  66. for opt, arg in cmd_line_options:
  67. if opt == '-h':
  68. print(cmd_line_help)
  69. sys.exit()
  70. elif opt == '--shellfile':
  71. cmd_line_shellfile = arg
  72. # Logging ##
  73. log = logging.getLogger('base')
  74. log.setLevel(logging.DEBUG)
  75. # log.setLevel(logging.WARNING)
  76. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  77. handler = logging.StreamHandler()
  78. handler.setFormatter(formatter)
  79. log.addHandler(handler)
  80. # Version
  81. version = 8.905
  82. version_date = "2019/01/28"
  83. beta = True
  84. # URL for update checks and statistics
  85. version_url = "http://flatcam.org/version"
  86. # App URL
  87. app_url = "http://flatcam.org"
  88. # Manual URL
  89. manual_url = "http://flatcam.org/manual/index.html"
  90. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  91. should_we_quit = True
  92. ##################
  93. ## Signals ##
  94. ##################
  95. # Inform the user
  96. # Handled by:
  97. # * App.info() --> Print on the status bar
  98. inform = QtCore.pyqtSignal(str)
  99. # General purpose background task
  100. worker_task = QtCore.pyqtSignal(dict)
  101. # File opened
  102. # Handled by:
  103. # * register_folder()
  104. # * register_recent()
  105. # Note: Setting the parameters to unicode does not seem
  106. # to have an effect. Then are received as Qstring
  107. # anyway.
  108. # File type and filename
  109. file_opened = QtCore.pyqtSignal(str, str)
  110. # File type and filename
  111. file_saved = QtCore.pyqtSignal(str, str)
  112. # Percentage of progress
  113. progress = QtCore.pyqtSignal(int)
  114. plots_updated = QtCore.pyqtSignal()
  115. # Emitted by new_object() and passes the new object as argument, plot flag.
  116. # on_object_created() adds the object to the collection, plots on appropriate flag
  117. # and emits new_object_available.
  118. object_created = QtCore.pyqtSignal(object, bool, bool)
  119. # Emitted when a object has been changed (like scaled, mirrored)
  120. object_changed = QtCore.pyqtSignal(object)
  121. # Emitted after object has been plotted.
  122. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  123. object_plotted = QtCore.pyqtSignal(object)
  124. # Emitted when a new object has been added to the collection
  125. # and is ready to be used.
  126. new_object_available = QtCore.pyqtSignal(object)
  127. message = QtCore.pyqtSignal(str, str, str)
  128. # Emmited when shell command is finished(one command only)
  129. shell_command_finished = QtCore.pyqtSignal(object)
  130. # Emitted when multiprocess pool has been recreated
  131. pool_recreated = QtCore.pyqtSignal(object)
  132. # Emitted when an unhandled exception happens
  133. # in the worker task.
  134. thread_exception = QtCore.pyqtSignal(object)
  135. def __init__(self, user_defaults=True, post_gui=None):
  136. """
  137. Starts the application.
  138. :return: app
  139. :rtype: App
  140. """
  141. App.log.info("FlatCAM Starting...")
  142. ###################
  143. ### OS-specific ###
  144. ###################
  145. # Folder for user settings.
  146. if sys.platform == 'win32':
  147. from win32com.shell import shell, shellcon
  148. if platform.architecture()[0] == '32bit':
  149. App.log.debug("Win32!")
  150. else:
  151. App.log.debug("Win64!")
  152. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + \
  153. '\FlatCAM'
  154. self.os = 'windows'
  155. else: # Linux/Unix/MacOS
  156. self.data_path = os.path.expanduser('~') + \
  157. '/.FlatCAM'
  158. self.os = 'unix'
  159. ###############################
  160. ### Setup folders and files ###
  161. ###############################
  162. if not os.path.exists(self.data_path):
  163. os.makedirs(self.data_path)
  164. App.log.debug('Created data folder: ' + self.data_path)
  165. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  166. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  167. self.postprocessorpaths = os.path.join(self.data_path,'postprocessors')
  168. if not os.path.exists(self.postprocessorpaths):
  169. os.makedirs(self.postprocessorpaths)
  170. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  171. # create current_defaults.FlatConfig file if there is none
  172. try:
  173. f = open(self.data_path + '/current_defaults.FlatConfig')
  174. f.close()
  175. except IOError:
  176. App.log.debug('Creating empty current_defaults.FlatConfig')
  177. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  178. json.dump({}, f)
  179. f.close()
  180. # create factory_defaults.FlatConfig file if there is none
  181. try:
  182. f = open(self.data_path + '/factory_defaults.FlatConfig')
  183. f.close()
  184. except IOError:
  185. App.log.debug('Creating empty factory_defaults.FlatConfig')
  186. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  187. json.dump({}, f)
  188. f.close()
  189. try:
  190. f = open(self.data_path + '/recent.json')
  191. f.close()
  192. except IOError:
  193. App.log.debug('Creating empty recent.json')
  194. f = open(self.data_path + '/recent.json', 'w')
  195. json.dump([], f)
  196. f.close()
  197. # Application directory. CHDIR to it. Otherwise, trying to load
  198. # GUI icons will fail as their path is relative.
  199. # This will fail under cx_freeze ...
  200. self.app_home = os.path.dirname(os.path.realpath(__file__))
  201. App.log.debug("Application path is " + self.app_home)
  202. App.log.debug("Started in " + os.getcwd())
  203. # cx_freeze workaround
  204. if os.path.isfile(self.app_home):
  205. self.app_home = os.path.dirname(self.app_home)
  206. os.chdir(self.app_home)
  207. # Create multiprocessing pool
  208. self.pool = Pool()
  209. ####################
  210. ## Initialize GUI ##
  211. ####################
  212. # FlatCAM colors used in plotting
  213. self.FC_light_green = '#BBF268BF'
  214. self.FC_dark_green = '#006E20BF'
  215. self.FC_light_blue = '#a5a5ffbf'
  216. self.FC_dark_blue = '#0000ffbf'
  217. QtCore.QObject.__init__(self)
  218. self.ui = FlatCAMGUI(self.version, self.beta, self)
  219. # self.connect(self.ui,
  220. # QtCore.SIGNAL("geomUpdate(int, int, int, int, int)"),
  221. # self.save_geometry) PyQt4
  222. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  223. self.ui.final_save.connect(self.final_save)
  224. ##############
  225. #### Data ####
  226. ##############
  227. self.recent = []
  228. self.clipboard = QtWidgets.QApplication.clipboard()
  229. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  230. self.project_filename = None
  231. self.toggle_units_ignore = False
  232. # self.defaults_form = PreferencesUI()
  233. self.general_defaults_form = GeneralPreferencesUI()
  234. self.gerber_defaults_form = GerberPreferencesUI()
  235. self.excellon_defaults_form = ExcellonPreferencesUI()
  236. self.geometry_defaults_form = GeometryPreferencesUI()
  237. self.cncjob_defaults_form = CNCJobPreferencesUI()
  238. self.tools_defaults_form = ToolsPreferencesUI()
  239. # when adding entries here read the comments in the method found bellow named:
  240. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  241. self.defaults_form_fields = {
  242. "units": self.general_defaults_form.general_app_group.units_radio,
  243. "global_shell_at_startup": self.general_defaults_form.general_app_group.shell_startup_cb,
  244. "global_version_check": self.general_defaults_form.general_app_group.version_check_cb,
  245. "global_send_stats": self.general_defaults_form.general_app_group.send_stats_cb,
  246. "global_gridx": self.general_defaults_form.general_gui_group.gridx_entry,
  247. "global_gridy": self.general_defaults_form.general_gui_group.gridy_entry,
  248. "global_plot_fill": self.general_defaults_form.general_gui_group.pf_color_entry,
  249. "global_plot_line": self.general_defaults_form.general_gui_group.pl_color_entry,
  250. "global_sel_fill": self.general_defaults_form.general_gui_group.sf_color_entry,
  251. "global_sel_line": self.general_defaults_form.general_gui_group.sl_color_entry,
  252. "global_alt_sel_fill": self.general_defaults_form.general_gui_group.alt_sf_color_entry,
  253. "global_alt_sel_line": self.general_defaults_form.general_gui_group.alt_sl_color_entry,
  254. "global_draw_color": self.general_defaults_form.general_gui_group.draw_color_entry,
  255. "global_sel_draw_color": self.general_defaults_form.general_gui_group.sel_draw_color_entry,
  256. "global_pan_button": self.general_defaults_form.general_app_group.pan_button_radio,
  257. "global_mselect_key": self.general_defaults_form.general_app_group.mselect_radio,
  258. # "global_pan_with_space_key": self.general_defaults_form.general_gui_group.pan_with_space_cb,
  259. "global_workspace": self.general_defaults_form.general_gui_group.workspace_cb,
  260. "global_workspaceT": self.general_defaults_form.general_gui_group.wk_cb,
  261. "gerber_plot": self.gerber_defaults_form.gerber_group.plot_cb,
  262. "gerber_solid": self.gerber_defaults_form.gerber_group.solid_cb,
  263. "gerber_multicolored": self.gerber_defaults_form.gerber_group.multicolored_cb,
  264. "gerber_isotooldia": self.gerber_defaults_form.gerber_group.iso_tool_dia_entry,
  265. "gerber_isopasses": self.gerber_defaults_form.gerber_group.iso_width_entry,
  266. "gerber_isooverlap": self.gerber_defaults_form.gerber_group.iso_overlap_entry,
  267. "gerber_combine_passes": self.gerber_defaults_form.gerber_group.combine_passes_cb,
  268. "gerber_milling_type": self.gerber_defaults_form.gerber_group.milling_type_radio,
  269. "gerber_noncoppermargin": self.gerber_defaults_form.gerber_group.noncopper_margin_entry,
  270. "gerber_noncopperrounded": self.gerber_defaults_form.gerber_group.noncopper_rounded_cb,
  271. "gerber_bboxmargin": self.gerber_defaults_form.gerber_group.bbmargin_entry,
  272. "gerber_bboxrounded": self.gerber_defaults_form.gerber_group.bbrounded_cb,
  273. "gerber_circle_steps": self.gerber_defaults_form.gerber_group.circle_steps_entry,
  274. "excellon_plot": self.excellon_defaults_form.excellon_gen_group.plot_cb,
  275. "excellon_solid": self.excellon_defaults_form.excellon_gen_group.solid_cb,
  276. "excellon_format_upper_in": self.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  277. "excellon_format_lower_in": self.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  278. "excellon_format_upper_mm": self.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  279. "excellon_format_lower_mm": self.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  280. "excellon_zeros": self.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  281. "excellon_units": self.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  282. "excellon_optimization_type": self.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  283. "excellon_drillz": self.excellon_defaults_form.excellon_opt_group.cutz_entry,
  284. "excellon_travelz": self.excellon_defaults_form.excellon_opt_group.travelz_entry,
  285. "excellon_feedrate": self.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  286. "excellon_feedrate_rapid": self.excellon_defaults_form.excellon_opt_group.feedrate_rapid_entry,
  287. "excellon_spindlespeed": self.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  288. "excellon_dwell": self.excellon_defaults_form.excellon_opt_group.dwell_cb,
  289. "excellon_dwelltime": self.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  290. "excellon_toolchange": self.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  291. "excellon_toolchangez": self.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  292. "excellon_toolchangexy": self.excellon_defaults_form.excellon_opt_group.toolchangexy_entry,
  293. "excellon_ppname_e": self.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  294. "excellon_startz": self.excellon_defaults_form.excellon_opt_group.estartz_entry,
  295. "excellon_endz": self.excellon_defaults_form.excellon_opt_group.eendz_entry,
  296. "excellon_tooldia": self.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  297. "excellon_slot_tooldia": self.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  298. "excellon_gcode_type": self.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  299. "geometry_plot": self.geometry_defaults_form.geometry_group.plot_cb,
  300. "geometry_segx": self.geometry_defaults_form.geometry_group.segx_entry,
  301. "geometry_segy": self.geometry_defaults_form.geometry_group.segy_entry,
  302. "geometry_cutz": self.geometry_defaults_form.geometry_group.cutz_entry,
  303. "geometry_travelz": self.geometry_defaults_form.geometry_group.travelz_entry,
  304. "geometry_feedrate": self.geometry_defaults_form.geometry_group.cncfeedrate_entry,
  305. "geometry_feedrate_z": self.geometry_defaults_form.geometry_group.cncplunge_entry,
  306. "geometry_feedrate_rapid": self.geometry_defaults_form.geometry_group.cncfeedrate_rapid_entry,
  307. "geometry_cnctooldia": self.geometry_defaults_form.geometry_group.cnctooldia_entry,
  308. "geometry_spindlespeed": self.geometry_defaults_form.geometry_group.cncspindlespeed_entry,
  309. "geometry_dwell": self.geometry_defaults_form.geometry_group.dwell_cb,
  310. "geometry_dwelltime": self.geometry_defaults_form.geometry_group.dwelltime_entry,
  311. "geometry_ppname_g": self.geometry_defaults_form.geometry_group.pp_geometry_name_cb,
  312. "geometry_toolchange": self.geometry_defaults_form.geometry_group.toolchange_cb,
  313. "geometry_toolchangez": self.geometry_defaults_form.geometry_group.toolchangez_entry,
  314. "geometry_toolchangexy": self.geometry_defaults_form.geometry_group.toolchangexy_entry,
  315. "geometry_startz": self.geometry_defaults_form.geometry_group.gstartz_entry,
  316. "geometry_endz": self.geometry_defaults_form.geometry_group.gendz_entry,
  317. "geometry_multidepth": self.geometry_defaults_form.geometry_group.multidepth_cb,
  318. "geometry_depthperpass": self.geometry_defaults_form.geometry_group.depthperpass_entry,
  319. "geometry_extracut": self.geometry_defaults_form.geometry_group.extracut_cb,
  320. "geometry_circle_steps": self.geometry_defaults_form.geometry_group.circle_steps_entry,
  321. "cncjob_plot": self.cncjob_defaults_form.cncjob_group.plot_cb,
  322. "cncjob_tooldia": self.cncjob_defaults_form.cncjob_group.tooldia_entry,
  323. "cncjob_coords_decimals": self.cncjob_defaults_form.cncjob_group.coords_dec_entry,
  324. "cncjob_fr_decimals": self.cncjob_defaults_form.cncjob_group.fr_dec_entry,
  325. "cncjob_prepend": self.cncjob_defaults_form.cncjob_group.prepend_text,
  326. "cncjob_append": self.cncjob_defaults_form.cncjob_group.append_text,
  327. "cncjob_steps_per_circle": self.cncjob_defaults_form.cncjob_group.steps_per_circle_entry,
  328. "tools_ncctools": self.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  329. "tools_nccoverlap": self.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  330. "tools_nccmargin": self.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  331. "tools_nccmethod": self.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  332. "tools_nccconnect": self.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  333. "tools_ncccontour": self.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  334. "tools_nccrest": self.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  335. "tools_cutouttooldia": self.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  336. "tools_cutoutmargin": self.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  337. "tools_cutoutgapsize": self.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  338. "tools_gaps_rect": self.tools_defaults_form.tools_cutout_group.gaps_radio,
  339. "tools_painttooldia": self.tools_defaults_form.tools_paint_group.painttooldia_entry,
  340. "tools_paintoverlap": self.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  341. "tools_paintmargin": self.tools_defaults_form.tools_paint_group.paintmargin_entry,
  342. "tools_paintmethod": self.tools_defaults_form.tools_paint_group.paintmethod_combo,
  343. "tools_selectmethod": self.tools_defaults_form.tools_paint_group.selectmethod_combo,
  344. "tools_pathconnect": self.tools_defaults_form.tools_paint_group.pathconnect_cb,
  345. "tools_paintcontour": self.tools_defaults_form.tools_paint_group.contour_cb
  346. }
  347. # loads postprocessors
  348. self.postprocessors = load_postprocessors(self)
  349. for name in list(self.postprocessors.keys()):
  350. self.geometry_defaults_form.geometry_group.pp_geometry_name_cb.addItem(name)
  351. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  352. if name == 'hpgl':
  353. continue
  354. self.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  355. self.defaults = LoudDict()
  356. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  357. self.defaults.update({
  358. "global_serial": 0,
  359. "global_stats": {},
  360. "units": "IN",
  361. "global_version_check": True,
  362. "global_send_stats": True,
  363. "global_gridx": 1.0,
  364. "global_gridy": 1.0,
  365. "global_plot_fill": '#BBF268BF',
  366. "global_plot_line": '#006E20BF',
  367. "global_sel_fill": '#a5a5ffbf',
  368. "global_sel_line": '#0000ffbf',
  369. "global_alt_sel_fill": '#BBF268BF',
  370. "global_alt_sel_line": '#006E20BF',
  371. "global_draw_color": '#FF0000',
  372. "global_sel_draw_color": '#0000FF',
  373. "global_pan_button": '2',
  374. "global_mselect_key": 'Control',
  375. # "global_pan_with_space_key": False,
  376. "global_workspace": False,
  377. "global_workspaceT": "A4P",
  378. "global_toolbar_view": 31,
  379. "global_background_timeout": 300000, # Default value is 5 minutes
  380. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  381. # (python trace only for unknown errors),
  382. # 1 = show trace(show trace allways),
  383. # 2 = (For the future).
  384. # Persistence
  385. "global_last_folder": None,
  386. "global_last_save_folder": None,
  387. # Default window geometry
  388. "global_def_win_x": 100,
  389. "global_def_win_y": 100,
  390. "global_def_win_w": 1024,
  391. "global_def_win_h": 650,
  392. # Constants...
  393. "global_defaults_save_period_ms": 20000, # Time between default saves.
  394. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  395. "global_shell_at_startup": False, # Show the shell at startup.
  396. "global_recent_limit": 10, # Max. items in recent list.
  397. "fit_key": '1',
  398. "zoom_out_key": '2',
  399. "zoom_in_key": '3',
  400. "grid_toggle_key": 'G',
  401. "zoom_ratio": 1.5,
  402. "global_point_clipboard_format": "(%.4f, %.4f)",
  403. "global_zdownrate": None,
  404. "gerber_plot": True,
  405. "gerber_solid": True,
  406. "gerber_multicolored": False,
  407. "gerber_isotooldia": 0.016,
  408. "gerber_isopasses": 1,
  409. "gerber_isooverlap": 0.15,
  410. "gerber_combine_passes": False,
  411. "gerber_milling_type": "cl",
  412. "gerber_noncoppermargin": 0.1,
  413. "gerber_noncopperrounded": False,
  414. "gerber_bboxmargin": 0.1,
  415. "gerber_bboxrounded": False,
  416. "gerber_circle_steps": 64,
  417. "gerber_use_buffer_for_union": True,
  418. "excellon_plot": True,
  419. "excellon_solid": True,
  420. "excellon_format_upper_in": 2,
  421. "excellon_format_lower_in": 4,
  422. "excellon_format_upper_mm": 3,
  423. "excellon_format_lower_mm": 3,
  424. "excellon_zeros": "L",
  425. "excellon_units": "INCH",
  426. "excellon_optimization_type": 'B',
  427. "excellon_search_time": 3,
  428. "excellon_drillz": -0.1,
  429. "excellon_travelz": 0.1,
  430. "excellon_feedrate": 3.0,
  431. "excellon_feedrate_rapid": 3.0,
  432. "excellon_spindlespeed": None,
  433. "excellon_dwell": False,
  434. "excellon_dwelltime": 1,
  435. "excellon_toolchange": False,
  436. "excellon_toolchangez": 1.0,
  437. "excellon_toolchangexy": "0.0, 0.0",
  438. "excellon_tooldia": 0.016,
  439. "excellon_slot_tooldia": 0.016,
  440. "excellon_startz": None,
  441. "excellon_endz": 2.0,
  442. "excellon_ppname_e": 'default',
  443. "excellon_gcode_type": "drills",
  444. "geometry_plot": True,
  445. "geometry_segx": 0.0,
  446. "geometry_segy": 0.0,
  447. "geometry_cutz": -0.002,
  448. "geometry_travelz": 0.1,
  449. "geometry_toolchange": False,
  450. "geometry_toolchangez": 1.0,
  451. "geometry_toolchangexy": "0.0, 0.0",
  452. "geometry_startz": None,
  453. "geometry_endz": 2.0,
  454. "geometry_feedrate": 3.0,
  455. "geometry_feedrate_z": 3.0,
  456. "geometry_feedrate_rapid": 3.0,
  457. "geometry_cnctooldia": 0.016,
  458. "geometry_spindlespeed": None,
  459. "geometry_dwell": False,
  460. "geometry_dwelltime": 1,
  461. "geometry_ppname_g": 'default',
  462. "geometry_depthperpass": 0.002,
  463. "geometry_multidepth": False,
  464. "geometry_extracut": False,
  465. "geometry_circle_steps": 64,
  466. "cncjob_plot": True,
  467. "cncjob_tooldia": 0.0393701,
  468. "cncjob_coords_decimals": 4,
  469. "cncjob_fr_decimals": 2,
  470. "cncjob_prepend": "",
  471. "cncjob_append": "",
  472. "cncjob_steps_per_circle": 64,
  473. "tools_ncctools": "1.0, 0.5",
  474. "tools_nccoverlap": 0.4,
  475. "tools_nccmargin": 0.1,
  476. "tools_nccmethod": "seed",
  477. "tools_nccconnect": True,
  478. "tools_ncccontour": True,
  479. "tools_nccrest": False,
  480. "tools_cutouttooldia": 0.1,
  481. "tools_cutoutmargin": 0.1,
  482. "tools_cutoutgapsize": 0.15,
  483. "tools_gaps_rect": "4",
  484. "tools_painttooldia": 0.07,
  485. "tools_paintoverlap": 0.15,
  486. "tools_paintmargin": 0.0,
  487. "tools_paintmethod": "seed",
  488. "tools_selectmethod": "single",
  489. "tools_pathconnect": True,
  490. "tools_paintcontour": True
  491. })
  492. ###############################
  493. ### Load defaults from file ###
  494. if user_defaults:
  495. self.load_defaults(filename='current_defaults')
  496. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  497. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  498. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  499. self.save_defaults(silent=True)
  500. self.propagate_defaults(silent=True)
  501. self.restore_main_win_geom()
  502. def auto_save_defaults():
  503. try:
  504. self.save_defaults(silent=True)
  505. self.propagate_defaults(silent=True)
  506. finally:
  507. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  508. # the following lines activates automatic defaults save
  509. # if user_defaults:
  510. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  511. # self.options_form = PreferencesUI()
  512. self.general_options_form = GeneralPreferencesUI()
  513. self.gerber_options_form = GerberPreferencesUI()
  514. self.excellon_options_form = ExcellonPreferencesUI()
  515. self.geometry_options_form = GeometryPreferencesUI()
  516. self.cncjob_options_form = CNCJobPreferencesUI()
  517. self.tools_options_form = ToolsPreferencesUI()
  518. self.options_form_fields = {
  519. "units": self.general_options_form.general_app_group.units_radio,
  520. "global_gridx": self.general_options_form.general_gui_group.gridx_entry,
  521. "global_gridy": self.general_options_form.general_gui_group.gridy_entry,
  522. "gerber_plot": self.gerber_options_form.gerber_group.plot_cb,
  523. "gerber_solid": self.gerber_options_form.gerber_group.solid_cb,
  524. "gerber_multicolored": self.gerber_options_form.gerber_group.multicolored_cb,
  525. "gerber_isotooldia": self.gerber_options_form.gerber_group.iso_tool_dia_entry,
  526. "gerber_isopasses": self.gerber_options_form.gerber_group.iso_width_entry,
  527. "gerber_isooverlap": self.gerber_options_form.gerber_group.iso_overlap_entry,
  528. "gerber_combine_passes": self.gerber_options_form.gerber_group.combine_passes_cb,
  529. "gerber_noncoppermargin": self.gerber_options_form.gerber_group.noncopper_margin_entry,
  530. "gerber_noncopperrounded": self.gerber_options_form.gerber_group.noncopper_rounded_cb,
  531. "gerber_bboxmargin": self.gerber_options_form.gerber_group.bbmargin_entry,
  532. "gerber_bboxrounded": self.gerber_options_form.gerber_group.bbrounded_cb,
  533. "excellon_plot": self.excellon_options_form.excellon_gen_group.plot_cb,
  534. "excellon_solid": self.excellon_options_form.excellon_gen_group.solid_cb,
  535. "excellon_format_upper_in": self.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  536. "excellon_format_lower_in": self.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  537. "excellon_format_upper_mm": self.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  538. "excellon_format_lower_mm": self.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  539. "excellon_zeros": self.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  540. "excellon_units": self.excellon_options_form.excellon_gen_group.excellon_units_radio,
  541. "excellon_optimization_type": self.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  542. "excellon_drillz": self.excellon_options_form.excellon_opt_group.cutz_entry,
  543. "excellon_travelz": self.excellon_options_form.excellon_opt_group.travelz_entry,
  544. "excellon_feedrate": self.excellon_options_form.excellon_opt_group.feedrate_entry,
  545. "excellon_feedrate_rapid": self.excellon_options_form.excellon_opt_group.feedrate_rapid_entry,
  546. "excellon_spindlespeed": self.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  547. "excellon_dwell": self.excellon_options_form.excellon_opt_group.dwell_cb,
  548. "excellon_dwelltime": self.excellon_options_form.excellon_opt_group.dwelltime_entry,
  549. "excellon_toolchange": self.excellon_options_form.excellon_opt_group.toolchange_cb,
  550. "excellon_toolchangez": self.excellon_options_form.excellon_opt_group.toolchangez_entry,
  551. "excellon_toolchangexy": self.excellon_options_form.excellon_opt_group.toolchangexy_entry,
  552. "excellon_tooldia": self.excellon_options_form.excellon_opt_group.tooldia_entry,
  553. "excellon_ppname_e": self.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  554. "excellon_startz": self.excellon_options_form.excellon_opt_group.estartz_entry,
  555. "excellon_endz": self.excellon_options_form.excellon_opt_group.eendz_entry,
  556. "geometry_plot": self.geometry_options_form.geometry_group.plot_cb,
  557. "geometry_segx": self.geometry_options_form.geometry_group.segx_entry,
  558. "geometry_segy": self.geometry_options_form.geometry_group.segy_entry,
  559. "geometry_cutz": self.geometry_options_form.geometry_group.cutz_entry,
  560. "geometry_travelz": self.geometry_options_form.geometry_group.travelz_entry,
  561. "geometry_feedrate": self.geometry_options_form.geometry_group.cncfeedrate_entry,
  562. "geometry_feedrate_z": self.geometry_options_form.geometry_group.cncplunge_entry,
  563. "geometry_feedrate_rapid": self.geometry_options_form.geometry_group.cncfeedrate_rapid_entry,
  564. "geometry_spindlespeed": self.geometry_options_form.geometry_group.cncspindlespeed_entry,
  565. "geometry_dwell": self.geometry_options_form.geometry_group.dwell_cb,
  566. "geometry_dwelltime": self.geometry_options_form.geometry_group.dwelltime_entry,
  567. "geometry_cnctooldia": self.geometry_options_form.geometry_group.cnctooldia_entry,
  568. "geometry_ppname_g": self.geometry_options_form.geometry_group.pp_geometry_name_cb,
  569. "geometry_toolchange": self.geometry_options_form.geometry_group.toolchange_cb,
  570. "geometry_toolchangez": self.geometry_options_form.geometry_group.toolchangez_entry,
  571. "geometry_toolchangexy": self.geometry_options_form.geometry_group.toolchangexy_entry,
  572. "geometry_startz": self.geometry_options_form.geometry_group.gstartz_entry,
  573. "geometry_endz": self.geometry_options_form.geometry_group.gendz_entry,
  574. "geometry_depthperpass": self.geometry_options_form.geometry_group.depthperpass_entry,
  575. "geometry_multidepth": self.geometry_options_form.geometry_group.multidepth_cb,
  576. "geometry_extracut": self.geometry_options_form.geometry_group.extracut_cb,
  577. "cncjob_plot": self.cncjob_options_form.cncjob_group.plot_cb,
  578. "cncjob_tooldia": self.cncjob_options_form.cncjob_group.tooldia_entry,
  579. "cncjob_prepend": self.cncjob_options_form.cncjob_group.prepend_text,
  580. "cncjob_append": self.cncjob_options_form.cncjob_group.append_text,
  581. "tools_ncctools": self.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  582. "tools_nccoverlap": self.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  583. "tools_nccmargin": self.tools_options_form.tools_ncc_group.ncc_margin_entry,
  584. "tools_cutouttooldia": self.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  585. "tools_cutoutmargin": self.tools_options_form.tools_cutout_group.cutout_margin_entry,
  586. "tools_cutoutgapsize": self.tools_options_form.tools_cutout_group.cutout_gap_entry,
  587. "tools_gaps": self.tools_options_form.tools_cutout_group.gaps_radio,
  588. "tools_painttooldia": self.tools_options_form.tools_paint_group.painttooldia_entry,
  589. "tools_paintoverlap": self.tools_options_form.tools_paint_group.paintoverlap_entry,
  590. "tools_paintmargin": self.tools_options_form.tools_paint_group.paintmargin_entry,
  591. "tools_paintmethod": self.tools_options_form.tools_paint_group.paintmethod_combo,
  592. "tools_selectmethod": self.tools_options_form.tools_paint_group.selectmethod_combo,
  593. "tools_pathconnect": self.tools_options_form.tools_paint_group.pathconnect_cb,
  594. "tools_paintcontour": self.tools_options_form.tools_paint_group.contour_cb
  595. }
  596. for name in list(self.postprocessors.keys()):
  597. self.geometry_options_form.geometry_group.pp_geometry_name_cb.addItem(name)
  598. self.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  599. self.options = LoudDict()
  600. self.options.set_change_callback(self.on_options_dict_change)
  601. self.options.update({
  602. "units": "IN",
  603. "global_gridx": 1.0,
  604. "global_gridy": 1.0,
  605. "global_background_timeout": 300000, # Default value is 5 minutes
  606. "global_verbose_error_level": 0, # Shell verbosity:
  607. # 0 = default(python trace only for unknown errors),
  608. # 1 = show trace(show trace allways), 2 = (For the future).
  609. "gerber_plot": True,
  610. "gerber_solid": True,
  611. "gerber_multicolored": False,
  612. "gerber_isotooldia": 0.016,
  613. "gerber_isopasses": 1,
  614. "gerber_isooverlap": 0.15,
  615. "gerber_combine_passes": True,
  616. "gerber_noncoppermargin": 0.0,
  617. "gerber_noncopperrounded": False,
  618. "gerber_bboxmargin": 0.0,
  619. "gerber_bboxrounded": False,
  620. "excellon_plot": True,
  621. "excellon_solid": False,
  622. "excellon_format_upper_in": 2,
  623. "excellon_format_lower_in": 4,
  624. "excellon_format_upper_mm": 3,
  625. "excellon_format_lower_mm": 3,
  626. "excellon_units": 'INCH',
  627. "excellon_optimization_type": 'B',
  628. "excellon_search_time": 3,
  629. "excellon_zeros": "L",
  630. "excellon_drillz": -0.1,
  631. "excellon_travelz": 0.1,
  632. "excellon_feedrate": 3.0,
  633. "excellon_feedrate_rapid": 3.0,
  634. "excellon_spindlespeed": None,
  635. "excellon_dwell": True,
  636. "excellon_dwelltime": 1000,
  637. "excellon_toolchange": False,
  638. "excellon_toolchangez": 1.0,
  639. "excellon_toolchangexy": "0.0, 0.0",
  640. "excellon_tooldia": 0.016,
  641. "excellon_ppname_e": 'default',
  642. "excellon_startz": None,
  643. "excellon_endz": 2.0,
  644. "geometry_plot": True,
  645. "geometry_segx": 0.0,
  646. "geometry_segy": 0.0,
  647. "geometry_cutz": -0.002,
  648. "geometry_travelz": 0.1,
  649. "geometry_feedrate": 3.0,
  650. "geometry_feedrate_z": 3.0,
  651. "geometry_feedrate_rapid": 3.0,
  652. "geometry_spindlespeed": None,
  653. "geometry_dwell": True,
  654. "geometry_dwelltime": 1000,
  655. "geometry_cnctooldia": 0.016,
  656. "geometry_toolchange": False,
  657. "geometry_toolchangez": 2.0,
  658. "geometry_toolchangexy": "0.0, 0.0",
  659. "geometry_startz": None,
  660. "geometry_endz": 2.0,
  661. "geometry_ppname_g": "default",
  662. "geometry_depthperpass": 0.002,
  663. "geometry_multidepth": False,
  664. "geometry_extracut": False,
  665. "cncjob_plot": True,
  666. "cncjob_tooldia": 0.016,
  667. "cncjob_prepend": "",
  668. "cncjob_append": "",
  669. "tools_ncctools": "1.0, 0.5",
  670. "tools_nccoverlap": 0.4,
  671. "tools_nccmargin": 1,
  672. "tools_cutouttooldia": 0.07,
  673. "tools_cutoutmargin": 0.1,
  674. "tools_cutoutgapsize": 0.15,
  675. "tools_gaps": "4",
  676. "tools_painttooldia": 0.07,
  677. "tools_paintoverlap": 0.15,
  678. "tools_paintmargin": 0.0,
  679. "tools_paintmethod": "seed",
  680. "tools_selectmethod": "single",
  681. "tools_pathconnect": True,
  682. "tools_paintcontour": True
  683. })
  684. self.options.update(self.defaults) # Copy app defaults to project options
  685. self.gen_form = None
  686. self.ger_form = None
  687. self.exc_form = None
  688. self.geo_form = None
  689. self.cnc_form = None
  690. self.tools_form = None
  691. self.on_options_combo_change(0) # Will show the initial form
  692. ### Define OBJECT COLLECTION ###
  693. self.collection = ObjectCollection(self)
  694. self.ui.project_tab_layout.addWidget(self.collection.view)
  695. ###
  696. self.log.debug("Finished creating Object Collection.")
  697. ### Initialize the color box's color in Preferences -> Global -> Color
  698. # Init Plot Colors
  699. self.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  700. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  701. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  702. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  703. int(self.defaults['global_plot_fill'][7:9], 16))
  704. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  705. int(self.defaults['global_plot_fill'][7:9], 16))
  706. self.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  707. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  708. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  709. # Init Left-Right Selection colors
  710. self.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  711. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  712. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  713. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  714. int(self.defaults['global_sel_fill'][7:9], 16))
  715. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  716. int(self.defaults['global_sel_fill'][7:9], 16))
  717. self.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  718. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  719. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  720. # Init Right-Left Selection colors
  721. self.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(self.defaults['global_alt_sel_fill'])
  722. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  723. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  724. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  725. int(self.defaults['global_sel_fill'][7:9], 16))
  726. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  727. int(self.defaults['global_sel_fill'][7:9], 16))
  728. self.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(self.defaults['global_alt_sel_line'])
  729. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  730. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  731. # Init Draw color and Selection Draw Color
  732. self.general_defaults_form.general_gui_group.draw_color_entry.set_value(self.defaults['global_draw_color'])
  733. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  734. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  735. self.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(self.defaults['global_sel_draw_color'])
  736. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  737. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  738. #### End of Data ####
  739. #### Plot Area ####
  740. start_plot_time = time.time() # debug
  741. self.plotcanvas = PlotCanvas(self.ui.right_layout, self)
  742. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  743. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  744. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  745. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  746. # Keys over plot enabled
  747. self.plotcanvas.vis_connect('key_press', self.on_key_over_plot)
  748. self.plotcanvas.vis_connect('key_release', self.on_key_release_over_plot)
  749. self.ui.splitter.setStretchFactor(1, 2)
  750. # So it can receive key presses
  751. self.plotcanvas.vispy_canvas.native.setFocus()
  752. self.app_cursor = self.plotcanvas.new_cursor()
  753. self.app_cursor.enabled = False
  754. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  755. # depending on from where those tools are called different actions can be done
  756. self.call_source = 'app'
  757. end_plot_time = time.time()
  758. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  759. ### EDITOR section
  760. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  761. self.exc_editor = FlatCAMExcEditor(self)
  762. # start with GRID activated
  763. self.ui.grid_snap_btn.trigger()
  764. self.ui.corner_snap_btn.setEnabled(False)
  765. self.ui.snap_max_dist_entry.setEnabled(False)
  766. self.ui.g_editor_cmenu.setEnabled(False)
  767. self.ui.e_editor_cmenu.setEnabled(False)
  768. #### Adjust tabs width ####
  769. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  770. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  771. self.collection.view.setMinimumWidth(290)
  772. self.log.debug("Finished adding Geometry and Excellon Editor's.")
  773. #### Worker ####
  774. self.workers = WorkerStack()
  775. self.worker_task.connect(self.workers.add_task)
  776. ### Signal handling ###
  777. ## Custom signals
  778. self.inform.connect(self.info)
  779. self.message.connect(self.message_dialog)
  780. self.progress.connect(self.set_progress_bar)
  781. self.object_created.connect(self.on_object_created)
  782. self.object_changed.connect(self.on_object_changed)
  783. self.object_plotted.connect(self.on_object_plotted)
  784. self.plots_updated.connect(self.on_plots_updated)
  785. self.file_opened.connect(self.register_recent)
  786. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  787. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  788. ## Standard signals
  789. # Menu
  790. self.ui.menufilenew.triggered.connect(self.on_file_new_click)
  791. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  792. self.ui.menufileopengerber_follow.triggered.connect(self.on_fileopengerber_follow)
  793. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  794. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  795. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  796. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  797. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  798. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  799. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  800. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  801. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  802. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  803. self.ui.menufileexportexcellon.triggered.connect(lambda: self.on_file_exportexcellon(altium_format=None))
  804. self.ui.menufileexportexcellon_altium.triggered.connect(lambda: self.on_file_exportexcellon(altium_format=True))
  805. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  806. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  807. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  808. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  809. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  810. self.ui.menufile_exit.triggered.connect(self.on_app_exit)
  811. self.ui.menueditnew.triggered.connect(lambda: self.new_object('geometry', 'new_g', lambda x, y: None))
  812. self.ui.menueditnewexc.triggered.connect(self.new_excellon_object)
  813. self.ui.menueditedit.triggered.connect(self.object2editor)
  814. self.ui.menueditok.triggered.connect(self.editor2object)
  815. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  816. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  817. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  818. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  819. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  820. self.ui.menueditdelete.triggered.connect(self.on_delete)
  821. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  822. self.ui.menueditcopyobjectasgeom.triggered.connect(self.on_copy_object_as_geometry)
  823. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  824. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  825. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  826. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  827. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  828. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  829. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  830. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  831. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  832. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  833. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  834. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  835. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  836. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  837. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  838. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  839. self.ui.menuviewdisableall.triggered.connect(lambda: self.disable_plots(self.collection.get_list()))
  840. self.ui.menuviewdisableother.triggered.connect(lambda: self.disable_plots(self.collection.get_non_selected()))
  841. self.ui.menuviewenable.triggered.connect(lambda: self.enable_plots(self.collection.get_list()))
  842. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  843. self.ui.menuview_zoom_in.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  844. self.ui.menuview_zoom_out.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  845. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  846. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  847. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  848. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  849. self.ui.menuhelp_about.triggered.connect(self.on_about)
  850. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  851. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  852. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  853. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  854. self.ui.menuprojectenable.triggered.connect(lambda: self.enable_plots(self.collection.get_selected()))
  855. self.ui.menuprojectdisable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  856. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  857. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  858. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  859. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  860. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  861. # Toolbar
  862. #self.ui.file_new_btn.triggered.connect(self.on_file_new)
  863. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  864. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  865. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  866. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  867. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  868. self.ui.replot_btn.triggered.connect(self.plot_all)
  869. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  870. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  871. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  872. self.ui.newgeo_btn.triggered.connect(lambda: self.new_object('geometry', 'new_g', lambda x, y: None))
  873. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  874. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  875. self.ui.update_obj_btn.triggered.connect(self.editor2object)
  876. self.ui.delete_btn.triggered.connect(self.on_delete)
  877. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  878. # Context Menu
  879. self.ui.popmenu_new_geo.triggered.connect(lambda: self.new_object('geometry', 'new_g', lambda x, y: None))
  880. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  881. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  882. self.ui.gridmenu_1.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.05"))
  883. self.ui.gridmenu_2.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.1"))
  884. self.ui.gridmenu_3.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.2"))
  885. self.ui.gridmenu_4.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.5"))
  886. self.ui.gridmenu_5.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("1.0"))
  887. self.ui.draw_line.triggered.connect(self.geo_editor.draw_tool_path)
  888. self.ui.draw_rect.triggered.connect(self.geo_editor.draw_tool_rectangle)
  889. self.ui.draw_cut.triggered.connect(self.geo_editor.cutpath)
  890. self.ui.draw_move.triggered.connect(self.geo_editor.on_move)
  891. self.ui.drill.triggered.connect(self.exc_editor.exc_add_drill)
  892. self.ui.drill_array.triggered.connect(self.exc_editor.exc_add_drill_array)
  893. self.ui.drill_copy.triggered.connect(self.exc_editor.exc_copy_drills)
  894. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  895. self.ui.clearplot.triggered.connect(self.clear_plots)
  896. self.ui.replot.triggered.connect(self.plot_all)
  897. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  898. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  899. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  900. self.ui.popmenu_save.triggered.connect(self.editor2object)
  901. self.ui.popmenu_move.triggered.connect(self.obj_move)
  902. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  903. # Preferences Plot Area TAB
  904. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  905. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  906. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  907. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  908. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  909. ###############################
  910. ### GUI PREFERENCES SIGNALS ###
  911. ###############################
  912. self.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  913. self.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(self.on_language_apply)
  914. ###############################
  915. ### GUI PREFERENCES SIGNALS ###
  916. ###############################
  917. # Setting plot colors signals
  918. self.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(self.on_pf_color_entry)
  919. self.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(self.on_pf_color_button)
  920. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(self.on_pf_color_spinner)
  921. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(self.on_pf_color_slider)
  922. self.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(self.on_pl_color_entry)
  923. self.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(self.on_pl_color_button)
  924. # Setting selection (left - right) colors signals
  925. self.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(self.on_sf_color_entry)
  926. self.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(self.on_sf_color_button)
  927. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(self.on_sf_color_spinner)
  928. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(self.on_sf_color_slider)
  929. self.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(self.on_sl_color_entry)
  930. self.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(self.on_sl_color_button)
  931. # Setting selection (right - left) colors signals
  932. self.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(self.on_alt_sf_color_entry)
  933. self.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(self.on_alt_sf_color_button)
  934. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  935. self.on_alt_sf_color_spinner)
  936. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  937. self.on_alt_sf_color_slider)
  938. self.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(self.on_alt_sl_color_entry)
  939. self.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(self.on_alt_sl_color_button)
  940. # Setting Editor Draw colors signals
  941. self.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(self.on_draw_color_entry)
  942. self.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(self.on_draw_color_button)
  943. self.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(self.on_sel_draw_color_entry)
  944. self.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(self.on_sel_draw_color_button)
  945. self.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  946. self.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  947. # Modify G-CODE Plot Area TAB
  948. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  949. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  950. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  951. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  952. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  953. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  954. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  955. # Object list
  956. self.collection.view.activated.connect(self.on_row_activated)
  957. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  958. self.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  959. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  960. self.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  961. self.on_excellon_defaults_button)
  962. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  963. self.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  964. self.on_excellon_options_button)
  965. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  966. self.tool_tab_locked = False
  967. ####################
  968. ### Other setups ###
  969. ####################
  970. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  971. self.setup_obj_classes()
  972. self.setup_recent_items()
  973. self.setup_component_editor()
  974. #############
  975. ### Shell ###
  976. #############
  977. ###
  978. # Auto-complete KEYWORDS
  979. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  980. 'aligndrill', 'clear',
  981. 'aligndrillgrid', 'cncjob', 'cutout', 'cutout_any', 'delete', 'drillcncjob',
  982. 'export_gcode',
  983. 'export_svg', 'ext', 'exteriors', 'follow', 'geo_union', 'geocutout', 'get_names',
  984. 'get_sys', 'getsys', 'help', 'import_svg', 'interiors', 'isolate', 'join_excellon',
  985. 'join_excellons', 'join_geometries', 'join_geometry', 'list_sys', 'listsys', 'mill',
  986. 'millholes', 'mirror', 'new', 'new_geometry', 'offset', 'open_excellon', 'open_gcode',
  987. 'open_gerber', 'open_project', 'options', 'paint', 'pan', 'panel', 'panelize', 'plot',
  988. 'save', 'save_project', 'save_sys', 'scale', 'set_active', 'set_sys', 'setsys',
  989. 'skew', 'subtract_poly', 'subtract_rectangle', 'version', 'write_gcode'
  990. ]
  991. self.ordinary_keywords = ['name', 'center_x', 'center_y', 'radius', 'x0', 'y0', 'x1', 'y1', 'box', 'axis',
  992. 'holes','grid', 'minoffset', 'gridoffset','axisoffset', 'dia', 'dist', 'gridoffsetx',
  993. 'gridoffsety', 'columns', 'rows', 'z_cut', 'z_move', 'feedrate', 'feedrate_rapid',
  994. 'tooldia', 'multidepth', 'extracut', 'depthperpass', 'ppname_g', 'outname', 'margin',
  995. 'gaps', 'gapsize', 'tools', 'drillz', 'travelz', 'spindlespeed', 'toolchange',
  996. 'toolchangez', 'endz', 'ppname_e', 'opt_type', 'preamble', 'postamble', 'filename',
  997. 'scale_factor', 'type', 'passes', 'overlap', 'combine', 'use_threads', 'x', 'y',
  998. 'follow', 'all', 'spacing_columns', 'spacing_rows', 'factor', 'value', 'angle_x',
  999. 'angle_y', 'gridx', 'gridy', 'True', 'False'
  1000. ]
  1001. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords
  1002. self.shell = FCShell(self, version=self.version)
  1003. self.shell._edit.set_model_data(self.myKeywords)
  1004. self.shell.setWindowIcon(self.ui.app_icon)
  1005. self.shell.setWindowTitle("FlatCAM Shell")
  1006. self.shell.resize(*self.defaults["global_shell_shape"])
  1007. self.shell.append_output("FlatCAM %s (c)2014-2019 Juan Pablo Caram " % self.version)
  1008. self.shell.append_output("(Type help to get started)\n\n")
  1009. self.init_tcl()
  1010. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1011. self.ui.shell_dock.setWidget(self.shell)
  1012. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1013. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1014. QtWidgets.QDockWidget.DockWidgetFloatable |
  1015. QtWidgets.QDockWidget.DockWidgetClosable)
  1016. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1017. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1018. if self.defaults["global_shell_at_startup"]:
  1019. self.ui.shell_dock.show()
  1020. else:
  1021. self.ui.shell_dock.hide()
  1022. #########################
  1023. ### Tools and Plugins ###
  1024. #########################
  1025. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1026. self.install_tools()
  1027. ### System Font Parsing ###
  1028. # self.f_parse = ParseFont(self)
  1029. # self.parse_system_fonts()
  1030. # test if the program was started with a script as parameter
  1031. if self.cmd_line_shellfile:
  1032. try:
  1033. with open(self.cmd_line_shellfile, "r") as myfile:
  1034. cmd_line_shellfile_text = myfile.read()
  1035. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1036. except Exception as ext:
  1037. print("ERROR: ", ext)
  1038. sys.exit(2)
  1039. ###########################
  1040. #### Check for updates ####
  1041. ###########################
  1042. # Separate thread (Not worker)
  1043. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1044. if (self.beta is False or self.beta is None) and \
  1045. self.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1046. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1047. self.thr2 = QtCore.QThread()
  1048. self.worker_task.emit({'fcn': self.version_check,
  1049. 'params': []})
  1050. self.thr2.start()
  1051. ####################################
  1052. #### Variables for global usage ####
  1053. ####################################
  1054. # coordinates for relative position display
  1055. self.rel_point1 = (0, 0)
  1056. self.rel_point2 = (0, 0)
  1057. # variable to store coordinates
  1058. self.pos = (0, 0)
  1059. self.pos_jump = (0, 0)
  1060. # variable to store if there was motion before right mouse button click (panning)
  1061. self.panning_action = False
  1062. # variable to store if a command is active (then the var is not None) and which one it is
  1063. self.command_active = None
  1064. # variable to store the status of moving selection action
  1065. # None value means that it's not an selection action
  1066. # True value = a selection from left to right
  1067. # False value = a selection from right to left
  1068. self.selection_type = None
  1069. # List to store the objects that are currently loaded in FlatCAM
  1070. # This list is updated on each object creation or object delete
  1071. self.all_objects_list = []
  1072. # List to store the objects that are selected
  1073. self.sel_objects_list = []
  1074. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1075. self.key_modifiers = None
  1076. # Variable to hold the status of the axis
  1077. self.toggle_axis = True
  1078. self.cursor = None
  1079. # Variable to store the GCODE that was edited
  1080. self.gcode_edited = ""
  1081. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3', 'gko',
  1082. 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15', 'dim', 'mil',
  1083. 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo', 'art', 'gbd']
  1084. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc']
  1085. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1086. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1087. 'mpf']
  1088. self.svg_list = ['svg']
  1089. self.dxf_list = ['dxf']
  1090. self.prj_list = ['flatprj']
  1091. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1092. # flag for polygons not cleared
  1093. self.poly_not_cleared = False
  1094. ### Save defaults to factory_defaults.FlatConfig file ###
  1095. ### It's done only once after install #############
  1096. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1097. fac_def_from_file = factory_file.read()
  1098. factory_defaults = json.loads(fac_def_from_file)
  1099. # if the file contain an empty dictionary then save the factory defaults into the file
  1100. if not factory_defaults:
  1101. self.save_factory_defaults(silent=False)
  1102. factory_file.close()
  1103. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1104. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1105. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1106. # Post-GUI initialization: Experimental attempt
  1107. # to perform unit tests on the GUI.
  1108. # if post_gui is not None:
  1109. # post_gui(self)
  1110. App.log.debug("END of constructor. Releasing control.")
  1111. # accept a project file as command line parameter
  1112. # the path/file_name must be enclosed in quotes if it contain spaces
  1113. for argument in App.args:
  1114. if '.FlatPrj' in argument:
  1115. try:
  1116. project_name = str(argument)
  1117. if project_name == "":
  1118. self.inform.emit("Open cancelled.")
  1119. else:
  1120. # self.open_project(project_name)
  1121. run_from_arg = True
  1122. self.worker_task.emit({'fcn': self.open_project,
  1123. 'params': [project_name, run_from_arg]})
  1124. except Exception as e:
  1125. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1126. def defaults_read_form(self):
  1127. for option in self.defaults_form_fields:
  1128. try:
  1129. self.defaults[option] = self.defaults_form_fields[option].get_value()
  1130. except:
  1131. pass
  1132. def defaults_write_form(self):
  1133. for option in self.defaults:
  1134. self.defaults_write_form_field(option)
  1135. # try:
  1136. # self.defaults_form_fields[option].set_value(self.defaults[option])
  1137. # except KeyError:
  1138. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1139. # # TODO: Rethink this?
  1140. # pass
  1141. def defaults_write_form_field(self, field):
  1142. try:
  1143. self.defaults_form_fields[field].set_value(self.defaults[field])
  1144. except KeyError:
  1145. #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1146. # TODO: Rethink this?
  1147. pass
  1148. def clear_pool(self):
  1149. self.pool.close()
  1150. self.pool = Pool()
  1151. self.pool_recreated.emit(self.pool)
  1152. gc.collect()
  1153. # the order that the tools are installed is important as they can depend on each other install position
  1154. def install_tools(self):
  1155. self.dblsidedtool = DblSidedTool(self)
  1156. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  1157. self.measurement_tool = Measurement(self)
  1158. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  1159. self.panelize_tool = Panelize(self)
  1160. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  1161. self.film_tool = Film(self)
  1162. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'), separator=True)
  1163. self.move_tool = ToolMove(self)
  1164. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  1165. before=self.ui.menueditorigin)
  1166. self.cutout_tool = ToolCutout(self)
  1167. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16.png'), pos=self.ui.menutool,
  1168. before=self.measurement_tool.menuAction)
  1169. self.ncclear_tool = NonCopperClear(self)
  1170. self.ncclear_tool.install(icon=QtGui.QIcon('share/flatcam_icon16.png'), pos=self.ui.menutool,
  1171. before=self.measurement_tool.menuAction, separator=True)
  1172. self.paint_tool = ToolPaint(self)
  1173. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  1174. before=self.measurement_tool.menuAction, separator=True)
  1175. self.calculator_tool = ToolCalculator(self)
  1176. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'))
  1177. self.transform_tool = ToolTransform(self)
  1178. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  1179. self.properties_tool = Properties(self)
  1180. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  1181. self.image_tool = ToolImage(self)
  1182. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  1183. separator=True)
  1184. self.log.debug("Tools are installed.")
  1185. def init_tools(self):
  1186. # delete the data currently in the Tools Tab and the Tab itself
  1187. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1188. if widget is not None:
  1189. widget.deleteLater()
  1190. self.ui.notebook.removeTab(2)
  1191. # rebuild the Tools Tab
  1192. self.ui.tool_tab = QtWidgets.QWidget()
  1193. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1194. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1195. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1196. self.ui.tool_scroll_area = VerticalScrollArea()
  1197. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1198. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1199. self.install_tools()
  1200. self.log.debug("Tools are initialized.")
  1201. # def parse_system_fonts(self):
  1202. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1203. # 'params': []})
  1204. def object2editor(self):
  1205. """
  1206. Send the current Geometry or Excellon object (if any) into the editor.
  1207. :return: None
  1208. """
  1209. # adjust the visibility of some of the canvas context menu
  1210. self.ui.popmenu_edit.setVisible(False)
  1211. self.ui.popmenu_save.setVisible(True)
  1212. if isinstance(self.collection.get_active(), FlatCAMGeometry):
  1213. edited_object = self.collection.get_active()
  1214. # for now, if the Geometry is MultiGeo do not allow the editing
  1215. if edited_object.multigeo is True:
  1216. self.inform.emit("[warning_notcl]Editing a MultiGeo Geometry is not possible for the moment.")
  1217. return
  1218. self.ui.update_obj_btn.setEnabled(True)
  1219. self.geo_editor.edit_fcgeometry(edited_object)
  1220. self.ui.g_editor_cmenu.setEnabled(True)
  1221. # set call source to the Editor we go into
  1222. self.call_source = 'geo_editor'
  1223. # prevent the user to change anything in the Selected Tab while the Geo Editor is active
  1224. sel_tab_widget_list = self.ui.selected_tab.findChildren(QtWidgets.QWidget)
  1225. for w in sel_tab_widget_list:
  1226. w.setEnabled(False)
  1227. elif isinstance(self.collection.get_active(), FlatCAMExcellon):
  1228. self.ui.update_obj_btn.setEnabled(True)
  1229. self.exc_editor.edit_exc_obj(self.collection.get_active())
  1230. self.ui.e_editor_cmenu.setEnabled(True)
  1231. # set call source to the Editor we go into
  1232. self.call_source = 'exc_editor'
  1233. else:
  1234. self.inform.emit("[warning_notcl]Select a Geometry or Excellon Object to edit.")
  1235. return
  1236. # make sure that we can't select another object while in Editor Mode:
  1237. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1238. # delete any selection shape that might be active as they are not relevant in Editor
  1239. self.delete_selection_shape()
  1240. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1241. self.inform.emit("[warning_notcl]Editor is activated ...")
  1242. def editor2object(self):
  1243. """
  1244. Transfers the Geometry or Excellon from the editor to the current object.
  1245. :return: None
  1246. """
  1247. # adjust the visibility of some of the canvas context menu
  1248. self.ui.popmenu_edit.setVisible(True)
  1249. self.ui.popmenu_save.setVisible(False)
  1250. edited_obj = self.collection.get_active()
  1251. obj_type = ""
  1252. if isinstance(edited_obj, FlatCAMGeometry):
  1253. obj_type = "Geometry"
  1254. self.geo_editor.update_fcgeometry(edited_obj)
  1255. self.geo_editor.update_options(edited_obj)
  1256. self.geo_editor.deactivate()
  1257. # edited_obj.on_tool_delete(all=True)
  1258. # edited_obj.on_tool_add(dia=edited_obj.options['cnctooldia'])
  1259. self.ui.corner_snap_btn.setEnabled(False)
  1260. self.ui.update_obj_btn.setEnabled(False)
  1261. self.ui.g_editor_cmenu.setEnabled(False)
  1262. self.ui.e_editor_cmenu.setEnabled(False)
  1263. # update the geo object options so it is including the bounding box values
  1264. try:
  1265. xmin, ymin, xmax, ymax = edited_obj.bounds()
  1266. edited_obj.options['xmin'] = xmin
  1267. edited_obj.options['ymin'] = ymin
  1268. edited_obj.options['xmax'] = xmax
  1269. edited_obj.options['ymax'] = ymax
  1270. except AttributeError:
  1271. self.inform.emit("[warning] Object empty after edit.")
  1272. elif isinstance(edited_obj, FlatCAMExcellon):
  1273. obj_type = "Excellon"
  1274. self.exc_editor.update_exc_obj(edited_obj)
  1275. self.exc_editor.deactivate()
  1276. self.ui.corner_snap_btn.setEnabled(False)
  1277. self.ui.update_obj_btn.setEnabled(False)
  1278. self.ui.g_editor_cmenu.setEnabled(False)
  1279. self.ui.e_editor_cmenu.setEnabled(False)
  1280. else:
  1281. self.inform.emit("[warning_notcl]Select a Geometry or Excellon Object to update.")
  1282. return
  1283. # restore the call_source to app
  1284. self.call_source = 'app'
  1285. edited_obj.plot()
  1286. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1287. self.inform.emit("[success] %s is updated, returning to App..." % obj_type)
  1288. # reset the Object UI to original settings
  1289. # edited_obj.set_ui(edited_obj.ui_type())
  1290. # edited_obj.build_ui()
  1291. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1292. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1293. def get_last_folder(self):
  1294. return self.defaults["global_last_folder"]
  1295. def get_last_save_folder(self):
  1296. return self.defaults["global_last_save_folder"]
  1297. def report_usage(self, resource):
  1298. """
  1299. Increments usage counter for the given resource
  1300. in self.defaults['global_stats'].
  1301. :param resource: Name of the resource.
  1302. :return: None
  1303. """
  1304. if resource in self.defaults['global_stats']:
  1305. self.defaults['global_stats'][resource] += 1
  1306. else:
  1307. self.defaults['global_stats'][resource] = 1
  1308. def init_tcl(self):
  1309. if hasattr(self,'tcl'):
  1310. # self.tcl = None
  1311. # TODO we need to clean non default variables and procedures here
  1312. # new object cannot be used here as it will not remember values created for next passes,
  1313. # because tcl was execudted in old instance of TCL
  1314. pass
  1315. else:
  1316. self.tcl = tk.Tcl()
  1317. self.setup_shell()
  1318. self.log.debug("TCL Shell has been initialized.")
  1319. # TODO: This shouldn't be here.
  1320. class TclErrorException(Exception):
  1321. """
  1322. this exception is deffined here, to be able catch it if we sucessfully handle all errors from shell command
  1323. """
  1324. pass
  1325. def shell_message(self, msg, show=False, error=False):
  1326. """
  1327. Shows a message on the FlatCAM Shell
  1328. :param msg: Message to display.
  1329. :param show: Opens the shell.
  1330. :param error: Shows the message as an error.
  1331. :return: None
  1332. """
  1333. if show:
  1334. self.ui.shell_dock.show()
  1335. try:
  1336. if error:
  1337. self.shell.append_error(msg + "\n")
  1338. else:
  1339. self.shell.append_output(msg + "\n")
  1340. except AttributeError:
  1341. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  1342. def raise_tcl_unknown_error(self, unknownException):
  1343. """
  1344. Raise exception if is different type than TclErrorException
  1345. this is here mainly to show unknown errors inside TCL shell console.
  1346. :param unknownException:
  1347. :return:
  1348. """
  1349. if not isinstance(unknownException, self.TclErrorException):
  1350. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  1351. else:
  1352. raise unknownException
  1353. def display_tcl_error(self, error, error_info=None):
  1354. """
  1355. escape bracket [ with \ otherwise there is error
  1356. "ERROR: missing close-bracket" instead of real error
  1357. :param error: it may be text or exception
  1358. :return: None
  1359. """
  1360. if isinstance(error, Exception):
  1361. exc_type, exc_value, exc_traceback = error_info
  1362. if not isinstance(error, self.TclErrorException):
  1363. show_trace = 1
  1364. else:
  1365. show_trace = int(self.defaults['global_verbose_error_level'])
  1366. if show_trace > 0:
  1367. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  1368. trc_formated = []
  1369. for a in reversed(trc):
  1370. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  1371. text = "%s\nPython traceback: %s\n%s" % (exc_value,
  1372. exc_type,
  1373. "\n".join(trc_formated))
  1374. else:
  1375. text = "%s" % error
  1376. else:
  1377. text = error
  1378. text = text.replace('[', '\\[').replace('"', '\\"')
  1379. self.tcl.eval('return -code error "%s"' % text)
  1380. def raise_tcl_error(self, text):
  1381. """
  1382. this method pass exception from python into TCL as error, so we get stacktrace and reason
  1383. :param text: text of error
  1384. :return: raise exception
  1385. """
  1386. self.display_tcl_error(text)
  1387. raise self.TclErrorException(text)
  1388. def exec_command(self, text):
  1389. """
  1390. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1391. Also handles execution in separated threads
  1392. :param text:
  1393. :return: output if there was any
  1394. """
  1395. self.report_usage('exec_command')
  1396. result = self.exec_command_test(text, False)
  1397. #MS: added this method call so the geometry is updated once the TCL
  1398. #command is executed
  1399. self.plot_all()
  1400. return result
  1401. def exec_command_test(self, text, reraise=True):
  1402. """
  1403. Same as exec_command(...) with additional control over exceptions.
  1404. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1405. :param text: Input command
  1406. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  1407. :return: Output from the command
  1408. """
  1409. text = str(text)
  1410. try:
  1411. self.shell.open_proccessing() # Disables input box.
  1412. result = self.tcl.eval(str(text))
  1413. if result != 'None':
  1414. self.shell.append_output(result + '\n')
  1415. except tk.TclError as e:
  1416. # This will display more precise answer if something in TCL shell fails
  1417. result = self.tcl.eval("set errorInfo")
  1418. self.log.error("Exec command Exception: %s" % (result + '\n'))
  1419. self.shell.append_error('ERROR: ' + result + '\n')
  1420. # Show error in console and just return or in test raise exception
  1421. if reraise:
  1422. raise e
  1423. finally:
  1424. self.shell.close_proccessing()
  1425. pass
  1426. return result
  1427. # """
  1428. # Code below is unsused. Saved for later.
  1429. # """
  1430. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  1431. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  1432. # self.log.debug(parts)
  1433. # try:
  1434. # if parts[0] not in commands:
  1435. # self.shell.append_error("Unknown command\n")
  1436. # return
  1437. #
  1438. # #import inspect
  1439. # #inspect.getargspec(someMethod)
  1440. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  1441. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  1442. # self.shell.append_error(
  1443. # "Command %s takes %d arguments. %d given.\n" %
  1444. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  1445. # )
  1446. # return
  1447. #
  1448. # cmdfcn = commands[parts[0]]["fcn"]
  1449. # cmdconv = commands[parts[0]]["converters"]
  1450. # if len(parts) - 1 > 0:
  1451. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  1452. # else:
  1453. # retval = cmdfcn()
  1454. # retfcn = commands[parts[0]]["retfcn"]
  1455. # if retval and retfcn(retval):
  1456. # self.shell.append_output(retfcn(retval) + "\n")
  1457. #
  1458. # except Exception as e:
  1459. # #self.shell.append_error(''.join(traceback.format_exc()))
  1460. # #self.shell.append_error("?\n")
  1461. # self.shell.append_error(str(e) + "\n")
  1462. def info(self, msg):
  1463. """
  1464. Informs the user. Normally on the status bar, optionally
  1465. also on the shell.
  1466. :param msg: Text to write.
  1467. :return: None
  1468. """
  1469. # Type of message in brackets at the begining of the message.
  1470. match = re.search("\[([^\]]+)\](.*)", msg)
  1471. if match:
  1472. level = match.group(1)
  1473. msg_ = match.group(2)
  1474. self.ui.fcinfo.set_status(str(msg_), level=level)
  1475. if level == "error" or level == "warning":
  1476. self.shell_message(msg, error=True, show=True)
  1477. elif level == "error_notcl" or level == "warning_notcl":
  1478. self.shell_message(msg, error=True, show=False)
  1479. else:
  1480. self.shell_message(msg, error=False, show=False)
  1481. else:
  1482. self.ui.fcinfo.set_status(str(msg), level="info")
  1483. # make sure that if the message is to clear the infobar with a space
  1484. # is not printed over and over on the shell
  1485. if msg != '':
  1486. self.shell_message(msg)
  1487. def restore_toolbar_view(self):
  1488. tb = self.defaults["global_toolbar_view"]
  1489. if tb & 1:
  1490. self.ui.toolbarfile.setVisible(True)
  1491. else:
  1492. self.ui.toolbarfile.setVisible(False)
  1493. if tb & 2:
  1494. self.ui.toolbargeo.setVisible(True)
  1495. else:
  1496. self.ui.toolbargeo.setVisible(False)
  1497. if tb & 4:
  1498. self.ui.toolbarview.setVisible(True)
  1499. else:
  1500. self.ui.toolbarview.setVisible(False)
  1501. if tb & 8:
  1502. self.ui.toolbartools.setVisible(True)
  1503. else:
  1504. self.ui.toolbartools.setVisible(False)
  1505. if tb & 16:
  1506. self.ui.snap_toolbar.setVisible(True)
  1507. else:
  1508. self.ui.snap_toolbar.setVisible(False)
  1509. def load_defaults(self, filename):
  1510. """
  1511. Loads the aplication's default settings from current_defaults.FlatConfig into
  1512. ``self.defaults``.
  1513. :return: None
  1514. """
  1515. try:
  1516. f = open(self.data_path + "/" + filename + ".FlatConfig")
  1517. options = f.read()
  1518. f.close()
  1519. except IOError:
  1520. self.log.error("Could not load defaults file.")
  1521. self.inform.emit("[error] Could not load defaults file.")
  1522. # in case the defaults file can't be loaded, show all toolbars
  1523. self.defaults["global_toolbar_view"] = 31
  1524. return
  1525. try:
  1526. defaults = json.loads(options)
  1527. except:
  1528. # in case the defaults file can't be loaded, show all toolbars
  1529. self.defaults["global_toolbar_view"] = 31
  1530. e = sys.exc_info()[0]
  1531. App.log.error(str(e))
  1532. self.inform.emit("[error] Failed to parse defaults file.")
  1533. return
  1534. self.defaults.update(defaults)
  1535. log.debug("FlatCAM defaults loaded from: %s" % filename)
  1536. # restore the toolbar view
  1537. self.restore_toolbar_view()
  1538. def on_import_preferences(self):
  1539. """
  1540. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  1541. ``self.defaults``.
  1542. :return: None
  1543. """
  1544. self.report_usage("on_import_preferences")
  1545. App.log.debug("on_import_preferences()")
  1546. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1547. try:
  1548. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import FlatCAM Preferences",
  1549. directory=self.data_path, filter=filter)
  1550. except TypeError:
  1551. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import FlatCAM Preferences", filter=filter)
  1552. filename = str(filename)
  1553. if filename == "":
  1554. self.inform.emit("[warning_notcl]FlatCAM preferences import cancelled.")
  1555. else:
  1556. try:
  1557. f = open(filename)
  1558. options = f.read()
  1559. f.close()
  1560. except IOError:
  1561. self.log.error("Could not load defaults file.")
  1562. self.inform.emit("[error_notcl] Could not load defaults file.")
  1563. return
  1564. try:
  1565. defaults_from_file = json.loads(options)
  1566. except:
  1567. e = sys.exc_info()[0]
  1568. App.log.error(str(e))
  1569. self.inform.emit("[error_notcl] Failed to parse defaults file.")
  1570. return
  1571. self.defaults.update(defaults_from_file)
  1572. self.inform.emit("[success]Imported Defaults from %s" %filename)
  1573. def on_export_preferences(self):
  1574. self.report_usage("on_export_preferences")
  1575. App.log.debug("on_export_preferences()")
  1576. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1577. try:
  1578. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export FlatCAM Preferences",
  1579. directory=self.data_path, filter=filter)
  1580. except TypeError:
  1581. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export FlatCAM Preferences", filter=filter)
  1582. filename = str(filename)
  1583. defaults_from_file = {}
  1584. if filename == "":
  1585. self.inform.emit("[warning_notcl]FlatCAM preferences export cancelled.")
  1586. return
  1587. else:
  1588. try:
  1589. f = open(filename, 'w')
  1590. defaults_file_content = f.read()
  1591. f.close()
  1592. except IOError:
  1593. App.log.debug('Creating a new preferences file ...')
  1594. f = open(filename, 'w')
  1595. json.dump({}, f)
  1596. f.close()
  1597. except:
  1598. e = sys.exc_info()[0]
  1599. App.log.error("Could not load defaults file.")
  1600. App.log.error(str(e))
  1601. self.inform.emit("[error_notcl]Could not load defaults file.")
  1602. return
  1603. try:
  1604. defaults_from_file = json.loads(defaults_file_content)
  1605. except:
  1606. App.log.warning("Trying to read an empty Preferences file. Continue.")
  1607. # Update options
  1608. self.defaults_read_form()
  1609. defaults_from_file.update(self.defaults)
  1610. self.propagate_defaults(silent=True)
  1611. # Save update options
  1612. try:
  1613. f = open(filename, "w")
  1614. json.dump(defaults_from_file, f)
  1615. f.close()
  1616. except:
  1617. self.inform.emit("[error_notcl] Failed to write defaults to file.")
  1618. return
  1619. self.inform.emit("[success]Exported Defaults to %s" % filename)
  1620. def on_preferences_open_folder(self):
  1621. if sys.platform == 'win32':
  1622. subprocess.Popen('explorer %s' % self.data_path)
  1623. elif sys.platform == 'darwin':
  1624. os.system('open "%s"' % self.data_path)
  1625. else:
  1626. subprocess.Popen(['xdg-open', self.data_path])
  1627. self.inform.emit("[success]FlatCAM Preferences Folder opened.")
  1628. def save_geometry(self, x, y, width, height, notebook_width):
  1629. self.defaults["global_def_win_x"] = x
  1630. self.defaults["global_def_win_y"] = y
  1631. self.defaults["global_def_win_w"] = width
  1632. self.defaults["global_def_win_h"] = height
  1633. self.defaults["def_notebook_width"] = notebook_width
  1634. self.save_defaults()
  1635. def message_dialog(self, title, message, kind="info"):
  1636. icon = {"info": QtWidgets.QMessageBox.Information,
  1637. "warning": QtWidgets.QMessageBox.Warning,
  1638. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  1639. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  1640. dlg.setText(message)
  1641. dlg.exec_()
  1642. def register_recent(self, kind, filename):
  1643. self.log.debug("register_recent()")
  1644. self.log.debug(" %s" % kind)
  1645. self.log.debug(" %s" % filename)
  1646. record = {'kind': str(kind), 'filename': str(filename)}
  1647. if record in self.recent:
  1648. return
  1649. self.recent.insert(0, record)
  1650. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  1651. self.recent.pop()
  1652. try:
  1653. f = open(self.data_path + '/recent.json', 'w')
  1654. except IOError:
  1655. App.log.error("Failed to open recent items file for writing.")
  1656. self.inform.emit('[error_notcl]Failed to open recent files file for writing.')
  1657. return
  1658. #try:
  1659. json.dump(self.recent, f)
  1660. # except:
  1661. # App.log.error("Failed to write to recent items file.")
  1662. # self.inform.emit('ERROR: Failed to write to recent items file.')
  1663. # f.close()
  1664. f.close()
  1665. # Re-buid the recent items menu
  1666. self.setup_recent_items()
  1667. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  1668. """
  1669. Creates a new specalized FlatCAMObj and attaches it to the application,
  1670. this is, updates the GUI accordingly, any other records and plots it.
  1671. This method is thread-safe.
  1672. Notes:
  1673. * If the name is in use, the self.collection will modify it
  1674. when appending it to the collection. There is no need to handle
  1675. name conflicts here.
  1676. :param kind: The kind of object to create. One of 'gerber',
  1677. 'excellon', 'cncjob' and 'geometry'.
  1678. :type kind: str
  1679. :param name: Name for the object.
  1680. :type name: str
  1681. :param initialize: Function to run after creation of the object
  1682. but before it is attached to the application. The function is
  1683. called with 2 parameters: the new object and the App instance.
  1684. :type initialize: function
  1685. :return: None
  1686. :rtype: None
  1687. """
  1688. App.log.debug("new_object()")
  1689. self.plot = plot
  1690. self.autoselected = autoselected
  1691. t0 = time.time() # Debug
  1692. ## Create object
  1693. classdict = {
  1694. "gerber": FlatCAMGerber,
  1695. "excellon": FlatCAMExcellon,
  1696. "cncjob": FlatCAMCNCjob,
  1697. "geometry": FlatCAMGeometry
  1698. }
  1699. App.log.debug("Calling object constructor...")
  1700. obj = classdict[kind](name)
  1701. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  1702. # Set options from "Project options" form
  1703. self.options_read_form()
  1704. # IMPORTANT
  1705. # The key names in defaults and options dictionary's are not random:
  1706. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  1707. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  1708. # the options from project options form into the self.options. After that, below, depending on the type of
  1709. # object that is created, it will strip the name of the object and the underline (if the original key was
  1710. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  1711. # "toolchange"
  1712. for option in self.options:
  1713. if option.find(kind + "_") == 0:
  1714. oname = option[len(kind) + 1:]
  1715. obj.options[oname] = self.options[option]
  1716. # if kind == 'geometry':
  1717. # obj.tools = {}
  1718. # elif kind == 'cncjob':
  1719. # obj.cnc_tools = {}
  1720. # Initialize as per user request
  1721. # User must take care to implement initialize
  1722. # in a thread-safe way as is is likely that we
  1723. # have been invoked in a separate thread.
  1724. t1 = time.time()
  1725. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  1726. try:
  1727. return_value = initialize(obj, self)
  1728. except Exception as e:
  1729. if str(e) == "Empty Geometry":
  1730. self.inform.emit("[error_notcl] Object (%s) failed because: %s" % (kind, str(e)))
  1731. else:
  1732. self.inform.emit("[error] Object (%s) failed because: %s" % (kind, str(e)))
  1733. return "fail"
  1734. t2 = time.time()
  1735. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  1736. if return_value == 'fail':
  1737. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  1738. return "fail"
  1739. # Check units and convert if necessary
  1740. # This condition CAN be true because initialize() can change obj.units
  1741. if self.options["units"].upper() != obj.units.upper():
  1742. self.inform.emit("Converting units to " + self.options["units"] + ".")
  1743. obj.convert_units(self.options["units"])
  1744. t3 = time.time()
  1745. self.log.debug("%f seconds converting units." % (t3 - t2))
  1746. # Create the bounding box for the object and then add the results to the obj.options
  1747. try:
  1748. xmin, ymin, xmax, ymax = obj.bounds()
  1749. obj.options['xmin'] = xmin
  1750. obj.options['ymin'] = ymin
  1751. obj.options['xmax'] = xmax
  1752. obj.options['ymax'] = ymax
  1753. except:
  1754. log.warning("The object has no bounds properties.")
  1755. pass
  1756. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  1757. # Move the object to the main thread and let the app know that it is available.
  1758. obj.moveToThread(QtWidgets.QApplication.instance().thread())
  1759. self.object_created.emit(obj, self.plot, self.autoselected)
  1760. return obj
  1761. def new_excellon_object(self):
  1762. self.new_object('excellon', 'new_e', lambda x, y: None)
  1763. def on_object_created(self, obj, plot, autoselect):
  1764. """
  1765. Event callback for object creation.
  1766. :param obj: The newly created FlatCAM object.
  1767. :return: None
  1768. """
  1769. t0 = time.time() # DEBUG
  1770. self.log.debug("on_object_created()")
  1771. # The Collection might change the name if there is a collision
  1772. self.collection.append(obj)
  1773. # after adding the object to the collection always update the list of objects that are in the collection
  1774. self.all_objects_list = self.collection.get_list()
  1775. self.inform.emit("[success]Object (%s) created: %s" % (obj.kind, obj.options['name']))
  1776. self.new_object_available.emit(obj)
  1777. # update the SHELL auto-completer model with the name of the new object
  1778. self.myKeywords.append(obj.options['name'])
  1779. self.shell._edit.set_model_data(self.myKeywords)
  1780. if autoselect:
  1781. # select the just opened object but deselect the previous ones
  1782. self.collection.set_all_inactive()
  1783. self.collection.set_active(obj.options["name"])
  1784. def worker_task(obj):
  1785. with self.proc_container.new("Plotting"):
  1786. obj.plot()
  1787. t1 = time.time() # DEBUG
  1788. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  1789. self.object_plotted.emit(obj)
  1790. # Send to worker
  1791. # self.worker.add_task(worker_task, [self])
  1792. if plot:
  1793. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  1794. def on_object_changed(self, obj):
  1795. # update the bounding box data from obj.options
  1796. xmin, ymin, xmax, ymax = obj.bounds()
  1797. obj.options['xmin'] = xmin
  1798. obj.options['ymin'] = ymin
  1799. obj.options['xmax'] = xmax
  1800. obj.options['ymax'] = ymax
  1801. log.debug("Object changed, updating the bounding box data on self.options")
  1802. # delete the old selection shape
  1803. self.delete_selection_shape()
  1804. def on_object_plotted(self, obj):
  1805. self.on_zoom_fit(None)
  1806. def options_read_form(self):
  1807. for option in self.options_form_fields:
  1808. self.options[option] = self.options_form_fields[option].get_value()
  1809. def options_write_form(self):
  1810. for option in self.options:
  1811. self.options_write_form_field(option)
  1812. def options_write_form_field(self, field):
  1813. try:
  1814. self.options_form_fields[field].set_value(self.options[field])
  1815. except KeyError:
  1816. # Changed from error to debug. This allows to have data stored
  1817. # which is not user-editable.
  1818. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  1819. pass
  1820. def on_about(self):
  1821. """
  1822. Displays the "about" dialog.
  1823. :return: None
  1824. """
  1825. self.report_usage("on_about")
  1826. version = self.version
  1827. version_date = self.version_date
  1828. beta = self.beta
  1829. class AboutDialog(QtWidgets.QDialog):
  1830. def __init__(self, parent=None):
  1831. QtWidgets.QDialog.__init__(self, parent)
  1832. # Icon and title
  1833. self.setWindowIcon(parent.app_icon)
  1834. self.setWindowTitle("FlatCAM")
  1835. layout1 = QtWidgets.QVBoxLayout()
  1836. self.setLayout(layout1)
  1837. layout2 = QtWidgets.QHBoxLayout()
  1838. layout1.addLayout(layout2)
  1839. logo = QtWidgets.QLabel()
  1840. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  1841. layout2.addWidget(logo, stretch=0)
  1842. title = QtWidgets.QLabel(
  1843. "<font size=8><B>FlatCAM</B></font><BR>"
  1844. "Version %s %s (%s) - %s <BR>"
  1845. "<BR>"
  1846. "2D Computer-Aided Printed Circuit Board<BR>"
  1847. "Manufacturing.<BR>"
  1848. "<BR>"
  1849. "(c) 2014-2019 <B>Juan Pablo Caram</B><BR>"
  1850. "<BR>"
  1851. "<B> Main Contributors:</B><BR>"
  1852. "Denis Hayrullin<BR>"
  1853. "Kamil Sopko<BR>"
  1854. "Marius Stanciu<BR>"
  1855. "Matthieu Berthomé<BR>"
  1856. "and many others found "
  1857. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  1858. "<BR>"
  1859. "Development is done "
  1860. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  1861. "DOWNLOAD area "
  1862. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  1863. "" % (version, ('BETA' if beta else ''), version_date, platform.architecture()[0])
  1864. )
  1865. title.setOpenExternalLinks(True)
  1866. layout2.addWidget(title, stretch=1)
  1867. layout3 = QtWidgets.QHBoxLayout()
  1868. layout1.addLayout(layout3)
  1869. layout3.addStretch()
  1870. okbtn = QtWidgets.QPushButton("Close")
  1871. layout3.addWidget(okbtn)
  1872. okbtn.clicked.connect(self.accept)
  1873. AboutDialog(self.ui).exec_()
  1874. def on_file_savedefaults(self):
  1875. """
  1876. Callback for menu item File->Save Defaults. Saves application default options
  1877. ``self.defaults`` to current_defaults.FlatConfig.
  1878. :return: None
  1879. """
  1880. self.save_defaults()
  1881. def on_app_exit(self):
  1882. if self.collection.get_list():
  1883. msgbox = QtWidgets.QMessageBox()
  1884. # msgbox.setText("<B>Save changes ...</B>")
  1885. msgbox.setText("There are files/objects opened in FlatCAM. "
  1886. "\n"
  1887. "Do you want to Save the project?")
  1888. msgbox.setWindowTitle("Save changes")
  1889. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  1890. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  1891. QtWidgets.QMessageBox.Cancel)
  1892. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  1893. response = msgbox.exec_()
  1894. if response == QtWidgets.QMessageBox.Yes:
  1895. self.on_file_saveprojectas(thread=False)
  1896. elif response == QtWidgets.QMessageBox.Cancel:
  1897. return
  1898. self.save_defaults()
  1899. else:
  1900. self.save_defaults()
  1901. log.debug("Application defaults saved ... Exit event.")
  1902. QtWidgets.qApp.quit()
  1903. def save_defaults(self, silent=False):
  1904. """
  1905. Saves application default options
  1906. ``self.defaults`` to current_defaults.FlatConfig.
  1907. :return: None
  1908. """
  1909. self.report_usage("save_defaults")
  1910. # Read options from file
  1911. try:
  1912. f = open(self.data_path + "/current_defaults.FlatConfig")
  1913. defaults_file_content = f.read()
  1914. f.close()
  1915. except:
  1916. e = sys.exc_info()[0]
  1917. App.log.error("Could not load defaults file.")
  1918. App.log.error(str(e))
  1919. self.inform.emit("[error_notcl] Could not load defaults file.")
  1920. return
  1921. try:
  1922. defaults = json.loads(defaults_file_content)
  1923. except:
  1924. e = sys.exc_info()[0]
  1925. App.log.error("Failed to parse defaults file.")
  1926. App.log.error(str(e))
  1927. self.inform.emit("[error_notcl] Failed to parse defaults file.")
  1928. return
  1929. # Update options
  1930. self.defaults_read_form()
  1931. defaults.update(self.defaults)
  1932. self.propagate_defaults(silent=True)
  1933. # Save update options
  1934. try:
  1935. f = open(self.data_path + "/current_defaults.FlatConfig", "w")
  1936. json.dump(defaults, f)
  1937. f.close()
  1938. except:
  1939. self.inform.emit("[error_notcl] Failed to write defaults to file.")
  1940. return
  1941. # Save the toolbar view
  1942. tb_status = 0
  1943. if self.ui.toolbarfile.isVisible():
  1944. tb_status += 1
  1945. if self.ui.toolbargeo.isVisible():
  1946. tb_status += 2
  1947. if self.ui.toolbarview.isVisible():
  1948. tb_status += 4
  1949. if self.ui.toolbartools.isVisible():
  1950. tb_status += 8
  1951. if self.ui.snap_toolbar.isVisible():
  1952. tb_status += 16
  1953. self.defaults["global_toolbar_view"] = tb_status
  1954. if not silent:
  1955. self.inform.emit("[success]Defaults saved.")
  1956. def save_factory_defaults(self, silent=False):
  1957. """
  1958. Saves application factory default options
  1959. ``self.defaults`` to factory_defaults.FlatConfig.
  1960. It's a one time job done just after the first install.
  1961. :return: None
  1962. """
  1963. self.report_usage("save_factory_defaults")
  1964. # Read options from file
  1965. try:
  1966. f_f_def = open(self.data_path + "/factory_defaults.FlatConfig")
  1967. factory_defaults_file_content = f_f_def.read()
  1968. f_f_def.close()
  1969. except:
  1970. e = sys.exc_info()[0]
  1971. App.log.error("Could not load factory defaults file.")
  1972. App.log.error(str(e))
  1973. self.inform.emit("[error_notcl] Could not load factory defaults file.")
  1974. return
  1975. try:
  1976. factory_defaults = json.loads(factory_defaults_file_content)
  1977. except:
  1978. e = sys.exc_info()[0]
  1979. App.log.error("Failed to parse factory defaults file.")
  1980. App.log.error(str(e))
  1981. self.inform.emit("[error_notcl] Failed to parse factory defaults file.")
  1982. return
  1983. # Update options
  1984. self.defaults_read_form()
  1985. factory_defaults.update(self.defaults)
  1986. self.propagate_defaults(silent=True)
  1987. # Save update options
  1988. try:
  1989. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  1990. json.dump(factory_defaults, f_f_def_s)
  1991. f_f_def_s.close()
  1992. except:
  1993. self.inform.emit("[error_notcl] Failed to write factory defaults to file.")
  1994. return
  1995. if silent is False:
  1996. self.inform.emit("Factory defaults saved.")
  1997. def final_save(self):
  1998. if self.collection.get_list():
  1999. msgbox = QtWidgets.QMessageBox()
  2000. # msgbox.setText("<B>Save changes ...</B>")
  2001. msgbox.setText("There are files/objects opened in FlatCAM. "
  2002. "\n"
  2003. "Do you want to Save the project?")
  2004. msgbox.setWindowTitle("Save changes")
  2005. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2006. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2007. QtWidgets.QMessageBox.Cancel)
  2008. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2009. response = msgbox.exec_()
  2010. if response == QtWidgets.QMessageBox.Yes:
  2011. self.on_file_saveprojectas(thread=False)
  2012. elif response == QtWidgets.QMessageBox.Cancel:
  2013. self.should_we_quit = False
  2014. return
  2015. self.save_defaults()
  2016. log.debug("Application defaults saved ... Exit event.")
  2017. def on_toggle_shell(self):
  2018. """
  2019. toggle shell if is visible close it if closed open it
  2020. :return:
  2021. """
  2022. if self.ui.shell_dock.isVisible():
  2023. self.ui.shell_dock.hide()
  2024. else:
  2025. self.ui.shell_dock.show()
  2026. def on_edit_join(self, name=None):
  2027. """
  2028. Callback for Edit->Join. Joins the selected geometry objects into
  2029. a new one.
  2030. :return: None
  2031. """
  2032. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2033. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2034. tooldias = []
  2035. geo_type_list = []
  2036. objs = self.collection.get_selected()
  2037. for obj in objs:
  2038. geo_type_list.append(obj.multigeo)
  2039. # if len(set(geo_type_list)) == 1 means that all list elements are the same
  2040. if len(set(geo_type_list)) != 1:
  2041. self.inform.emit("[error] Failed join. The Geometry objects are of different types.\n"
  2042. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2043. "convert from one to another and retry joining \n"
  2044. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2045. "the result may not be what was expected. \n"
  2046. "Check the generated GCODE.")
  2047. return
  2048. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2049. if True in geo_type_list:
  2050. def initialize(obj, app):
  2051. FlatCAMGeometry.merge(objs, obj, multigeo=True)
  2052. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2053. for v in obj.tools.values():
  2054. v['data']['name'] = obj_name_multi
  2055. self.new_object("geometry", obj_name_multi, initialize)
  2056. else:
  2057. def initialize(obj, app):
  2058. FlatCAMGeometry.merge(objs, obj, multigeo=False)
  2059. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2060. for v in obj.tools.values():
  2061. v['data']['name'] = obj_name_single
  2062. self.new_object("geometry", obj_name_single, initialize)
  2063. def on_edit_join_exc(self):
  2064. """
  2065. Callback for Edit->Join Excellon. Joins the selected excellon objects into
  2066. a new one.
  2067. :return: None
  2068. """
  2069. objs = self.collection.get_selected()
  2070. for obj in objs:
  2071. if not isinstance(obj, FlatCAMExcellon):
  2072. self.inform.emit("[error_notcl]Failed. Excellon joining works only on Excellon objects.")
  2073. return
  2074. def initialize(obj, app):
  2075. FlatCAMExcellon.merge(objs, obj)
  2076. self.new_object("excellon", 'Combo_Excellon', initialize)
  2077. def on_edit_join_grb(self):
  2078. """
  2079. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  2080. a new one.
  2081. :return: None
  2082. """
  2083. objs = self.collection.get_selected()
  2084. for obj in objs:
  2085. if not isinstance(obj, FlatCAMGerber):
  2086. self.inform.emit("[error_notcl]Failed. Gerber joining works only on Gerber objects.")
  2087. return
  2088. def initialize(obj, app):
  2089. FlatCAMGerber.merge(objs, obj)
  2090. self.new_object("gerber", 'Combo_Gerber', initialize)
  2091. def on_convert_singlegeo_to_multigeo(self):
  2092. obj = self.collection.get_active()
  2093. if obj is None:
  2094. self.inform.emit("[error_notcl]Failed. Select a Geometry Object and try again.")
  2095. return
  2096. if not isinstance(obj, FlatCAMGeometry):
  2097. self.inform.emit("[error_notcl]Expected a FlatCAMGeometry, got %s" % type(obj))
  2098. return
  2099. obj.multigeo = True
  2100. for tooluid, dict_value in obj.tools.items():
  2101. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  2102. if not isinstance(obj.solid_geometry, list):
  2103. obj.solid_geometry = [obj.solid_geometry]
  2104. obj.solid_geometry[:] = []
  2105. obj.plot()
  2106. self.inform.emit("[success] A Geometry object was converted to MultiGeo type.")
  2107. def on_convert_multigeo_to_singlegeo(self):
  2108. obj = self.collection.get_active()
  2109. if obj is None:
  2110. self.inform.emit("[error_notcl]Failed. Select a Geometry Object and try again.")
  2111. return
  2112. if not isinstance(obj, FlatCAMGeometry):
  2113. self.inform.emit("[error_notcl]Expected a FlatCAMGeometry, got %s" % type(obj))
  2114. return
  2115. obj.multigeo = False
  2116. total_solid_geometry = []
  2117. for tooluid, dict_value in obj.tools.items():
  2118. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  2119. # clear the original geometry
  2120. dict_value['solid_geometry'][:] = []
  2121. obj.solid_geometry = deepcopy(total_solid_geometry)
  2122. obj.plot()
  2123. self.inform.emit("[success] A Geometry object was converted to SingleGeo type.")
  2124. def on_options_dict_change(self, field):
  2125. self.options_write_form_field(field)
  2126. if field == "units":
  2127. self.set_screen_units(self.options['units'])
  2128. def on_defaults_dict_change(self, field):
  2129. self.defaults_write_form_field(field)
  2130. def set_screen_units(self, units):
  2131. self.ui.units_label.setText("[" + self.options["units"].lower() + "]")
  2132. def on_toggle_units(self):
  2133. """
  2134. Callback for the Units radio-button change in the Options tab.
  2135. Changes the application's default units or the current project's units.
  2136. If changing the project's units, the change propagates to all of
  2137. the objects in the project.
  2138. :return: None
  2139. """
  2140. self.report_usage("on_toggle_units")
  2141. if self.toggle_units_ignore:
  2142. return
  2143. # If option is the same, then ignore
  2144. if self.general_options_form.general_app_group.units_radio.get_value().upper() == self.options["units"].upper():
  2145. self.log.debug("on_toggle_units(): Same as options, so ignoring.")
  2146. return
  2147. # Options to scale
  2148. dimensions = ['gerber_isotooldia', 'tools_cutoutmargin', 'tools_cutoutgapsize',
  2149. 'gerber_noncoppermargin', 'gerber_bboxmargin','gerber_isooverlap','tools_nccoverlap',
  2150. 'tools_nccmargin','tools_cutouttooldia','tools_cutoutgapsize',
  2151. 'gerber_noncoppermargin','gerber_bboxmargin',
  2152. 'excellon_drillz', "excellon_toolchangexy",
  2153. 'excellon_travelz', 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  2154. 'excellon_tooldia', 'excellon_endz', 'cncjob_tooldia',
  2155. 'geometry_cutz', 'geometry_travelz', 'geometry_feedrate', 'geometry_feedrate_rapid',
  2156. 'geometry_cnctooldia', 'geometry_painttooldia', 'geometry_paintoverlap', 'geometry_toolchangexy',
  2157. 'geometry_toolchangez',
  2158. 'geometry_paintmargin', 'geometry_endz', 'geometry_depthperpass', 'global_gridx', 'global_gridy']
  2159. def scale_options(sfactor):
  2160. for dim in dimensions:
  2161. if dim == 'excellon_toolchangexy':
  2162. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  2163. coords_xy[0] *= sfactor
  2164. coords_xy[1] *= sfactor
  2165. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2166. elif dim == 'geometry_toolchangexy':
  2167. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  2168. coords_xy[0] *= sfactor
  2169. coords_xy[1] *= sfactor
  2170. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2171. else:
  2172. self.options[dim] *= sfactor
  2173. # The scaling factor depending on choice of units.
  2174. factor = 1/25.4
  2175. if self.general_options_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2176. factor = 25.4
  2177. # Changing project units. Warn user.
  2178. msgbox = QtWidgets.QMessageBox()
  2179. msgbox.setText("<B>Change project units ...</B>")
  2180. msgbox.setInformativeText("Changing the units of the project causes all geometrical "
  2181. "properties of all objects to be scaled accordingly. Continue?")
  2182. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Ok)
  2183. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2184. response = msgbox.exec_()
  2185. if response == QtWidgets.QMessageBox.Ok:
  2186. self.options_read_form()
  2187. scale_options(factor)
  2188. self.options_write_form()
  2189. # change this only if the workspace is active
  2190. if self.defaults['global_workspace'] is True:
  2191. self.plotcanvas.draw_workspace()
  2192. # adjust the grid values on the main toolbar
  2193. self.ui.grid_gap_x_entry.set_value(float(self.ui.grid_gap_x_entry.get_value()) * factor)
  2194. self.ui.grid_gap_y_entry.set_value(float(self.ui.grid_gap_y_entry.get_value()) * factor)
  2195. for obj in self.collection.get_list():
  2196. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  2197. obj.convert_units(units)
  2198. # make that the properties stored in the object are also updated
  2199. self.object_changed.emit(obj)
  2200. obj.build_ui()
  2201. current = self.collection.get_active()
  2202. if current is not None:
  2203. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  2204. if not isinstance(current, FlatCAMGeometry):
  2205. current.to_form()
  2206. self.plot_all()
  2207. else:
  2208. # Undo toggling
  2209. self.toggle_units_ignore = True
  2210. if self.general_options_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2211. self.general_options_form.general_app_group.units_radio.set_value('IN')
  2212. else:
  2213. self.general_options_form.general_app_group.units_radio.set_value('MM')
  2214. self.toggle_units_ignore = False
  2215. self.options_read_form()
  2216. self.inform.emit("Converted units to %s" % self.options["units"])
  2217. #self.ui.units_label.setText("[" + self.options["units"] + "]")
  2218. self.set_screen_units(self.options["units"])
  2219. def on_toggle_units_click(self):
  2220. if self.options["units"] == 'MM':
  2221. self.general_options_form.general_app_group.units_radio.set_value("IN")
  2222. else:
  2223. self.general_options_form.general_app_group.units_radio.set_value("MM")
  2224. self.on_toggle_units()
  2225. def on_language_apply(self):
  2226. # TODO: apply the language
  2227. # app restart section
  2228. pass
  2229. def on_toggle_axis(self):
  2230. if self.toggle_axis is False:
  2231. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2232. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2233. self.plotcanvas.redraw()
  2234. self.toggle_axis = True
  2235. else:
  2236. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2237. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2238. self.plotcanvas.redraw()
  2239. self.toggle_axis = False
  2240. def on_toggle_grid(self):
  2241. self.ui.grid_snap_btn.trigger()
  2242. def on_options_combo_change(self, sel):
  2243. """
  2244. Called when the combo box to choose between application defaults and
  2245. project option changes value. The corresponding variables are
  2246. copied to the UI.
  2247. :param sel: The option index that was chosen.
  2248. :return: None
  2249. """
  2250. # combo_sel = self.ui.notebook.combo_options.get_active()
  2251. App.log.debug("Options --> %s" % sel)
  2252. # form = [self.defaults_form, self.options_form][sel]
  2253. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  2254. if sel == 0:
  2255. self.gen_form = self.general_defaults_form
  2256. self.ger_form = self.gerber_defaults_form
  2257. self.exc_form = self.excellon_defaults_form
  2258. self.geo_form = self.geometry_defaults_form
  2259. self.cnc_form = self.cncjob_defaults_form
  2260. self.tools_form = self.tools_defaults_form
  2261. elif sel == 1:
  2262. self.gen_form = self.general_options_form
  2263. self.ger_form = self.gerber_options_form
  2264. self.exc_form = self.excellon_options_form
  2265. self.geo_form = self.geometry_options_form
  2266. self.cnc_form = self.cncjob_options_form
  2267. self.tools_form = self.tools_options_form
  2268. else:
  2269. return
  2270. try:
  2271. self.ui.general_scroll_area.takeWidget()
  2272. except:
  2273. self.log.debug("Nothing to remove")
  2274. self.ui.general_scroll_area.setWidget(self.gen_form)
  2275. self.gen_form.show()
  2276. try:
  2277. self.ui.gerber_scroll_area.takeWidget()
  2278. except:
  2279. self.log.debug("Nothing to remove")
  2280. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  2281. self.ger_form.show()
  2282. try:
  2283. self.ui.excellon_scroll_area.takeWidget()
  2284. except:
  2285. self.log.debug("Nothing to remove")
  2286. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  2287. self.exc_form.show()
  2288. try:
  2289. self.ui.geometry_scroll_area.takeWidget()
  2290. except:
  2291. self.log.debug("Nothing to remove")
  2292. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  2293. self.geo_form.show()
  2294. try:
  2295. self.ui.cncjob_scroll_area.takeWidget()
  2296. except:
  2297. self.log.debug("Nothing to remove")
  2298. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  2299. self.cnc_form.show()
  2300. try:
  2301. self.ui.tools_scroll_area.takeWidget()
  2302. except:
  2303. self.log.debug("Nothing to remove")
  2304. self.ui.tools_scroll_area.setWidget(self.tools_form)
  2305. self.tools_form.show()
  2306. self.log.debug("Finished GUI form initialization.")
  2307. # self.options2form()
  2308. def on_excellon_defaults_button(self):
  2309. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  2310. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  2311. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  2312. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  2313. self.defaults_form_fields["excellon_zeros"].set_value('L')
  2314. self.defaults_form_fields["excellon_units"].set_value('INCH')
  2315. log.debug("Excellon app defaults loaded ...")
  2316. def on_excellon_options_button(self):
  2317. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  2318. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  2319. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  2320. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  2321. self.options_form_fields["excellon_zeros"].set_value('L')
  2322. self.options_form_fields["excellon_units"].set_value('INCH')
  2323. log.debug("Excellon options defaults loaded ...")
  2324. # Setting plot colors handlers
  2325. def on_pf_color_entry(self):
  2326. self.defaults['global_plot_fill'] = self.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  2327. self.defaults['global_plot_fill'][7:9]
  2328. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2329. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  2330. def on_pf_color_button(self):
  2331. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  2332. c_dialog = QtWidgets.QColorDialog()
  2333. plot_fill_color = c_dialog.getColor(initial=current_color)
  2334. if plot_fill_color.isValid() is False:
  2335. return
  2336. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2337. "background-color:%s" % str(plot_fill_color.name()))
  2338. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  2339. self.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  2340. self.defaults['global_plot_fill'] = new_val
  2341. def on_pf_color_spinner(self):
  2342. spinner_value = self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  2343. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  2344. self.defaults['global_plot_fill'] = self.defaults['global_plot_fill'][:7] + \
  2345. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2346. self.defaults['global_plot_line'] = self.defaults['global_plot_line'][:7] + \
  2347. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2348. def on_pf_color_slider(self):
  2349. slider_value = self.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  2350. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  2351. def on_pl_color_entry(self):
  2352. self.defaults['global_plot_line'] = self.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  2353. self.defaults['global_plot_line'][7:9]
  2354. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2355. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  2356. def on_pl_color_button(self):
  2357. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  2358. # print(current_color)
  2359. c_dialog = QtWidgets.QColorDialog()
  2360. plot_line_color = c_dialog.getColor(initial=current_color)
  2361. if plot_line_color.isValid() is False:
  2362. return
  2363. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2364. "background-color:%s" % str(plot_line_color.name()))
  2365. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  2366. self.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  2367. self.defaults['global_plot_line'] = new_val_line
  2368. # Setting selection colors (left - right) handlers
  2369. def on_sf_color_entry(self):
  2370. self.defaults['global_sel_fill'] = self.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  2371. self.defaults['global_sel_fill'][7:9]
  2372. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2373. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  2374. def on_sf_color_button(self):
  2375. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  2376. c_dialog = QtWidgets.QColorDialog()
  2377. plot_fill_color = c_dialog.getColor(initial=current_color)
  2378. if plot_fill_color.isValid() is False:
  2379. return
  2380. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2381. "background-color:%s" % str(plot_fill_color.name()))
  2382. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  2383. self.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  2384. self.defaults['global_sel_fill'] = new_val
  2385. def on_sf_color_spinner(self):
  2386. spinner_value = self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  2387. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  2388. self.defaults['global_sel_fill'] = self.defaults['global_sel_fill'][:7] + \
  2389. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2390. self.defaults['global_sel_line'] = self.defaults['global_sel_line'][:7] + \
  2391. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2392. def on_sf_color_slider(self):
  2393. slider_value = self.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  2394. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  2395. def on_sl_color_entry(self):
  2396. self.defaults['global_sel_line'] = self.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  2397. self.defaults['global_sel_line'][7:9]
  2398. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2399. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  2400. def on_sl_color_button(self):
  2401. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  2402. c_dialog = QtWidgets.QColorDialog()
  2403. plot_line_color = c_dialog.getColor(initial=current_color)
  2404. if plot_line_color.isValid() is False:
  2405. return
  2406. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2407. "background-color:%s" % str(plot_line_color.name()))
  2408. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  2409. self.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  2410. self.defaults['global_sel_line'] = new_val_line
  2411. # Setting selection colors (right - left) handlers
  2412. def on_alt_sf_color_entry(self):
  2413. self.defaults['global_alt_sel_fill'] = self.general_defaults_form.general_gui_group \
  2414. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  2415. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2416. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  2417. def on_alt_sf_color_button(self):
  2418. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  2419. c_dialog = QtWidgets.QColorDialog()
  2420. plot_fill_color = c_dialog.getColor(initial=current_color)
  2421. if plot_fill_color.isValid() is False:
  2422. return
  2423. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2424. "background-color:%s" % str(plot_fill_color.name()))
  2425. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  2426. self.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  2427. self.defaults['global_alt_sel_fill'] = new_val
  2428. def on_alt_sf_color_spinner(self):
  2429. spinner_value = self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  2430. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  2431. self.defaults['global_alt_sel_fill'] = self.defaults['global_alt_sel_fill'][:7] + \
  2432. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2433. self.defaults['global_alt_sel_line'] = self.defaults['global_alt_sel_line'][:7] + \
  2434. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2435. def on_alt_sf_color_slider(self):
  2436. slider_value = self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  2437. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  2438. def on_alt_sl_color_entry(self):
  2439. self.defaults['global_alt_sel_line'] = self.general_defaults_form.general_gui_group \
  2440. .alt_sl_color_entry.get_value()[:7] + self.defaults['global_alt_sel_line'][7:9]
  2441. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2442. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  2443. def on_alt_sl_color_button(self):
  2444. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  2445. c_dialog = QtWidgets.QColorDialog()
  2446. plot_line_color = c_dialog.getColor(initial=current_color)
  2447. if plot_line_color.isValid() is False:
  2448. return
  2449. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2450. "background-color:%s" % str(plot_line_color.name()))
  2451. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  2452. self.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  2453. self.defaults['global_alt_sel_line'] = new_val_line
  2454. # Setting Editor colors
  2455. def on_draw_color_entry(self):
  2456. self.defaults['global_draw_color'] = self.general_defaults_form.general_gui_group \
  2457. .draw_color_entry.get_value()
  2458. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2459. "background-color:%s" % str(self.defaults['global_draw_color']))
  2460. def on_draw_color_button(self):
  2461. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  2462. c_dialog = QtWidgets.QColorDialog()
  2463. draw_color = c_dialog.getColor(initial=current_color)
  2464. if draw_color.isValid() is False:
  2465. return
  2466. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2467. "background-color:%s" % str(draw_color.name()))
  2468. new_val = str(draw_color.name())
  2469. self.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  2470. self.defaults['global_draw_color'] = new_val
  2471. def on_sel_draw_color_entry(self):
  2472. self.defaults['global_sel_draw_color'] = self.general_defaults_form.general_gui_group \
  2473. .sel_draw_color_entry.get_value()
  2474. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  2475. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  2476. def on_sel_draw_color_button(self):
  2477. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  2478. c_dialog = QtWidgets.QColorDialog()
  2479. sel_draw_color = c_dialog.getColor(initial=current_color)
  2480. if sel_draw_color.isValid() is False:
  2481. return
  2482. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  2483. "background-color:%s" % str(sel_draw_color.name()))
  2484. new_val_sel = str(sel_draw_color.name())
  2485. self.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  2486. self.defaults['global_sel_draw_color'] = new_val_sel
  2487. def on_workspace_modified(self):
  2488. self.save_defaults(silent=True)
  2489. self.plotcanvas.draw_workspace()
  2490. def on_workspace(self):
  2491. if self.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  2492. self.plotcanvas.restore_workspace()
  2493. else:
  2494. self.plotcanvas.delete_workspace()
  2495. self.save_defaults(silent=True)
  2496. def on_workspace_menu(self):
  2497. if self.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  2498. self.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  2499. else:
  2500. self.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  2501. self.on_workspace()
  2502. def on_save_button(self):
  2503. self.save_defaults(silent=False)
  2504. # load the defaults so they are updated into the app
  2505. self.load_defaults(filename='current_defaults')
  2506. # Re-fresh project options
  2507. self.on_options_app2project()
  2508. def handleOpen(self):
  2509. filter_group = " G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  2510. "All Files (*.*)"
  2511. path, _ = QtWidgets.QFileDialog.getOpenFileName(
  2512. caption='Open file', directory=self.get_last_folder(), filter=filter_group)
  2513. if path:
  2514. file = QtCore.QFile(path)
  2515. if file.open(QtCore.QIODevice.ReadOnly):
  2516. stream = QtCore.QTextStream(file)
  2517. self.gcode_edited = stream.readAll()
  2518. self.ui.code_editor.setPlainText(self.gcode_edited)
  2519. file.close()
  2520. def handlePrint(self):
  2521. dialog = QtPrintSupport.QPrintDialog()
  2522. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  2523. self.ui.code_editor.document().print_(dialog.printer())
  2524. def handlePreview(self):
  2525. dialog = QtPrintSupport.QPrintPreviewDialog()
  2526. dialog.paintRequested.connect(self.ui.code_editor.print_)
  2527. dialog.exec_()
  2528. def handleTextChanged(self):
  2529. # enable = not self.ui.code_editor.document().isEmpty()
  2530. # self.ui.buttonPrint.setEnabled(enable)
  2531. # self.ui.buttonPreview.setEnabled(enable)
  2532. pass
  2533. def handleSaveGCode(self):
  2534. _filter_ = " G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  2535. "All Files (*.*)"
  2536. try:
  2537. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  2538. caption="Export G-Code ...", directory=self.defaults["global_last_folder"], filter=_filter_)[0])
  2539. except TypeError:
  2540. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption="Export G-Code ...", filter=_filter_)[0])
  2541. try:
  2542. my_gcode = self.ui.code_editor.toPlainText()
  2543. with open(filename, 'w') as f:
  2544. for line in my_gcode:
  2545. f.write(line)
  2546. except FileNotFoundError:
  2547. self.inform.emit("[WARNING] No such file or directory")
  2548. return
  2549. # Just for adding it to the recent files list.
  2550. self.file_opened.emit("cncjob", filename)
  2551. self.file_saved.emit("cncjob", filename)
  2552. self.inform.emit("Saved to: " + filename)
  2553. def handleFindGCode(self):
  2554. flags = QtGui.QTextDocument.FindCaseSensitively
  2555. text_to_be_found = self.ui.entryFind.get_value()
  2556. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  2557. if r is False:
  2558. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  2559. def handleReplaceGCode(self):
  2560. old = self.ui.entryFind.get_value()
  2561. new = self.ui.entryReplace.get_value()
  2562. if self.ui.sel_all_cb.isChecked():
  2563. while True:
  2564. cursor = self.ui.code_editor.textCursor()
  2565. cursor.beginEditBlock()
  2566. flags = QtGui.QTextDocument.FindCaseSensitively
  2567. # self.ui.editor is the QPlainTextEdit
  2568. r = self.ui.code_editor.find(str(old), flags)
  2569. if r:
  2570. qc = self.ui.code_editor.textCursor()
  2571. if qc.hasSelection():
  2572. qc.insertText(new)
  2573. else:
  2574. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  2575. break
  2576. # Mark end of undo block
  2577. cursor.endEditBlock()
  2578. else:
  2579. cursor = self.ui.code_editor.textCursor()
  2580. cursor.beginEditBlock()
  2581. qc = self.ui.code_editor.textCursor()
  2582. if qc.hasSelection():
  2583. qc.insertText(new)
  2584. # Mark end of undo block
  2585. cursor.endEditBlock()
  2586. def on_new_geometry(self):
  2587. def initialize(obj, self):
  2588. obj.multitool = False
  2589. self.new_object('geometry', 'new_g', initialize)
  2590. self.plot_all()
  2591. def on_delete(self):
  2592. """
  2593. Delete the currently selected FlatCAMObjs.
  2594. :return: None
  2595. """
  2596. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  2597. # a geometry object before we update it.
  2598. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False:
  2599. if self.collection.get_active():
  2600. self.log.debug("on_delete()")
  2601. self.report_usage("on_delete")
  2602. while (self.collection.get_active()):
  2603. self.delete_first_selected()
  2604. self.inform.emit("Object(s) deleted ...")
  2605. # make sure that the selection shape is deleted, too
  2606. self.delete_selection_shape()
  2607. else:
  2608. self.inform.emit("Failed. No object(s) selected...")
  2609. else:
  2610. self.inform.emit("Save the work in Editor and try again ...")
  2611. def on_set_origin(self):
  2612. """
  2613. Set the origin to the left mouse click position
  2614. :return: None
  2615. """
  2616. #display the message for the user
  2617. #and ask him to click on the desired position
  2618. self.inform.emit('Click to set the origin ...')
  2619. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  2620. def on_jump_to(self):
  2621. """
  2622. Jump to a location by setting the mouse cursor location
  2623. :return:
  2624. """
  2625. dia_box = Dialog_box(title="Jump to Coordinates", label="Enter the coordinates in format X,Y:")
  2626. if dia_box.ok is True:
  2627. try:
  2628. location = eval(dia_box.location)
  2629. if not isinstance(location, tuple):
  2630. self.inform.emit("Wrong coordinates. Enter coordinates in format: X,Y")
  2631. return
  2632. except:
  2633. return
  2634. else:
  2635. return
  2636. self.plotcanvas.fit_center(loc=location)
  2637. cursor = QtGui.QCursor()
  2638. canvas_origin = self.plotcanvas.vispy_canvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  2639. jump_loc = self.plotcanvas.vispy_canvas.translate_coords_2((location[0], location[1]))
  2640. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  2641. self.inform.emit("Done.")
  2642. def on_copy_object(self):
  2643. def initialize(obj_init, app):
  2644. obj_init.solid_geometry = obj.solid_geometry
  2645. try:
  2646. if obj.tools:
  2647. obj_init.tools = obj.tools
  2648. except Exception as e:
  2649. log.debug("on_copy_object() --> %s" % str(e))
  2650. def initialize_excellon(obj_init, app):
  2651. obj_init.tools = obj.tools
  2652. # drills are offset, so they need to be deep copied
  2653. obj_init.drills = deepcopy(obj.drills)
  2654. # slots are offset, so they need to be deep copied
  2655. obj_init.slots = deepcopy(obj.slots)
  2656. obj_init.create_geometry()
  2657. for obj in self.collection.get_selected():
  2658. obj_name = obj.options["name"]
  2659. try:
  2660. if isinstance(obj, FlatCAMExcellon):
  2661. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  2662. elif isinstance(obj,FlatCAMGerber):
  2663. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  2664. elif isinstance(obj,FlatCAMGeometry):
  2665. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  2666. except Exception as e:
  2667. return "Operation failed: %s" % str(e)
  2668. def on_copy_object2(self, custom_name):
  2669. def initialize_geometry(obj_init, app):
  2670. obj_init.solid_geometry = obj.solid_geometry
  2671. try:
  2672. if obj.tools:
  2673. obj_init.tools = obj.tools
  2674. except Exception as e:
  2675. log.debug("on_copy_object2() --> %s" % str(e))
  2676. def initialize_gerber(obj_init, app):
  2677. obj_init.solid_geometry = obj.solid_geometry
  2678. obj_init.apertures = deepcopy(obj.apertures)
  2679. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  2680. def initialize_excellon(obj_init, app):
  2681. obj_init.tools = obj.tools
  2682. # drills are offset, so they need to be deep copied
  2683. obj_init.drills = deepcopy(obj.drills)
  2684. # slots are offset, so they need to be deep copied
  2685. obj_init.slots = deepcopy(obj.slots)
  2686. obj_init.create_geometry()
  2687. for obj in self.collection.get_selected():
  2688. obj_name = obj.options["name"]
  2689. try:
  2690. if isinstance(obj, FlatCAMExcellon):
  2691. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  2692. elif isinstance(obj,FlatCAMGerber):
  2693. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  2694. elif isinstance(obj,FlatCAMGeometry):
  2695. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  2696. except Exception as e:
  2697. return "Operation failed: %s" % str(e)
  2698. def on_rename_object(self, text):
  2699. named_obj = self.collection.get_active()
  2700. for obj in named_obj:
  2701. if obj is list:
  2702. self.on_rename_object(text)
  2703. else:
  2704. try:
  2705. obj.options['name'] = text
  2706. except:
  2707. log.warning("Could not rename the object in the list")
  2708. def on_copy_object_as_geometry(self):
  2709. def initialize(obj_init, app):
  2710. obj_init.solid_geometry = obj.solid_geometry
  2711. if obj.tools:
  2712. obj_init.tools = obj.tools
  2713. def initialize_excellon(obj, app):
  2714. objs = self.collection.get_selected()
  2715. FlatCAMGeometry.merge(objs, obj)
  2716. for obj in self.collection.get_selected():
  2717. obj_name = obj.options["name"]
  2718. try:
  2719. if isinstance(obj, FlatCAMExcellon):
  2720. self.new_object("geometry", str(obj_name) + "_gcopy", initialize_excellon)
  2721. else:
  2722. self.new_object("geometry", str(obj_name) + "_gcopy", initialize)
  2723. except Exception as e:
  2724. return "Operation failed: %s" % str(e)
  2725. def on_set_zero_click(self, event):
  2726. #this function will be available only for mouse left click
  2727. pos =[]
  2728. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  2729. if event.button == 1:
  2730. if self.grid_status() == True:
  2731. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  2732. else:
  2733. pos = pos_canvas
  2734. x = 0 - pos[0]
  2735. y = 0 - pos[1]
  2736. for obj in self.collection.get_list():
  2737. obj.offset((x,y))
  2738. self.object_changed.emit(obj)
  2739. # obj.plot()
  2740. self.plot_all()
  2741. self.inform.emit('[success] Origin set ...')
  2742. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  2743. def on_selectall(self):
  2744. # delete the possible selection box around a possible selected object
  2745. self.delete_selection_shape()
  2746. for name in self.collection.get_names():
  2747. self.collection.set_active(name)
  2748. curr_sel_obj = self.collection.get_by_name(name)
  2749. # create the selection box around the selected object
  2750. self.draw_selection_shape(curr_sel_obj)
  2751. def on_preferences(self):
  2752. # add the tab if it was closed
  2753. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, "Preferences")
  2754. # delete the absolute and relative position and messages in the infobar
  2755. self.ui.position_label.setText("")
  2756. self.ui.rel_position_label.setText("")
  2757. # Switch plot_area to preferences page
  2758. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  2759. self.ui.show()
  2760. def on_flipy(self):
  2761. obj_list = self.collection.get_selected()
  2762. xminlist = []
  2763. yminlist = []
  2764. xmaxlist = []
  2765. ymaxlist = []
  2766. if not obj_list:
  2767. self.inform.emit("[warning_notcl] No object selected.")
  2768. msg = "Please Select an object to flip!"
  2769. warningbox = QtWidgets.QMessageBox()
  2770. warningbox.setText(msg)
  2771. warningbox.setWindowTitle("Warning ...")
  2772. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2773. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2774. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2775. warningbox.exec_()
  2776. else:
  2777. try:
  2778. # first get a bounding box to fit all
  2779. for obj in obj_list:
  2780. xmin, ymin, xmax, ymax = obj.bounds()
  2781. xminlist.append(xmin)
  2782. yminlist.append(ymin)
  2783. xmaxlist.append(xmax)
  2784. ymaxlist.append(ymax)
  2785. # get the minimum x,y and maximum x,y for all objects selected
  2786. xminimal = min(xminlist)
  2787. yminimal = min(yminlist)
  2788. xmaximal = max(xmaxlist)
  2789. ymaximal = max(ymaxlist)
  2790. px = 0.5 * (xminimal + xmaximal)
  2791. py = 0.5 * (yminimal + ymaximal)
  2792. # execute mirroring
  2793. for obj in obj_list:
  2794. obj.mirror('X', [px, py])
  2795. obj.plot()
  2796. self.object_changed.emit(obj)
  2797. except Exception as e:
  2798. self.inform.emit("[error_notcl] Due of %s, Flip action was not executed." % str(e))
  2799. return
  2800. def on_flipx(self):
  2801. obj_list = self.collection.get_selected()
  2802. xminlist = []
  2803. yminlist = []
  2804. xmaxlist = []
  2805. ymaxlist = []
  2806. if not obj_list:
  2807. self.inform.emit("[warning_notcl] No object selected.")
  2808. msg = "Please Select an object to flip!"
  2809. warningbox = QtWidgets.QMessageBox()
  2810. warningbox.setText(msg)
  2811. warningbox.setWindowTitle("Warning ...")
  2812. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2813. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2814. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2815. warningbox.exec_()
  2816. else:
  2817. try:
  2818. # first get a bounding box to fit all
  2819. for obj in obj_list:
  2820. xmin, ymin, xmax, ymax = obj.bounds()
  2821. xminlist.append(xmin)
  2822. yminlist.append(ymin)
  2823. xmaxlist.append(xmax)
  2824. ymaxlist.append(ymax)
  2825. # get the minimum x,y and maximum x,y for all objects selected
  2826. xminimal = min(xminlist)
  2827. yminimal = min(yminlist)
  2828. xmaximal = max(xmaxlist)
  2829. ymaximal = max(ymaxlist)
  2830. px = 0.5 * (xminimal + xmaximal)
  2831. py = 0.5 * (yminimal + ymaximal)
  2832. # execute mirroring
  2833. for obj in obj_list:
  2834. obj.mirror('Y', [px, py])
  2835. obj.plot()
  2836. self.object_changed.emit(obj)
  2837. except Exception as e:
  2838. self.inform.emit("[error_notcl] Due of %s, Flip action was not executed." % str(e))
  2839. return
  2840. def on_rotate(self, silent=False, preset=None):
  2841. obj_list = self.collection.get_selected()
  2842. xminlist = []
  2843. yminlist = []
  2844. xmaxlist = []
  2845. ymaxlist = []
  2846. if not obj_list:
  2847. self.inform.emit("[warning_notcl] No object selected.")
  2848. msg = "Please Select an object to rotate!"
  2849. warningbox = QtWidgets.QMessageBox()
  2850. warningbox.setText(msg)
  2851. warningbox.setWindowTitle("Warning ...")
  2852. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2853. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2854. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2855. warningbox.exec_()
  2856. else:
  2857. if silent is False:
  2858. rotatebox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  2859. min=-360, max=360, decimals=3)
  2860. num, ok = rotatebox.get_value()
  2861. else:
  2862. num = preset
  2863. ok = True
  2864. if ok:
  2865. try:
  2866. # first get a bounding box to fit all
  2867. for obj in obj_list:
  2868. xmin, ymin, xmax, ymax = obj.bounds()
  2869. xminlist.append(xmin)
  2870. yminlist.append(ymin)
  2871. xmaxlist.append(xmax)
  2872. ymaxlist.append(ymax)
  2873. # get the minimum x,y and maximum x,y for all objects selected
  2874. xminimal = min(xminlist)
  2875. yminimal = min(yminlist)
  2876. xmaximal = max(xmaxlist)
  2877. ymaximal = max(ymaxlist)
  2878. px = 0.5 * (xminimal + xmaximal)
  2879. py = 0.5 * (yminimal + ymaximal)
  2880. for sel_obj in obj_list:
  2881. sel_obj.rotate(-num, point=(px, py))
  2882. sel_obj.plot()
  2883. self.object_changed.emit(sel_obj)
  2884. except Exception as e:
  2885. self.inform.emit("[error_notcl] Due of %s, rotation movement was not executed." % str(e))
  2886. return
  2887. def on_skewx(self):
  2888. obj_list = self.collection.get_selected()
  2889. xminlist = []
  2890. yminlist = []
  2891. if not obj_list:
  2892. self.inform.emit("[warning_notcl] No object selected.")
  2893. msg = "Please Select an object to skew/shear!"
  2894. warningbox = QtWidgets.QMessageBox()
  2895. warningbox.setText(msg)
  2896. warningbox.setWindowTitle("Warning ...")
  2897. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2898. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2899. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2900. warningbox.exec_()
  2901. else:
  2902. skewxbox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  2903. min=-360, max=360, decimals=3)
  2904. num, ok = skewxbox.get_value()
  2905. if ok:
  2906. # first get a bounding box to fit all
  2907. for obj in obj_list:
  2908. xmin, ymin, xmax, ymax = obj.bounds()
  2909. xminlist.append(xmin)
  2910. yminlist.append(ymin)
  2911. # get the minimum x,y and maximum x,y for all objects selected
  2912. xminimal = min(xminlist)
  2913. yminimal = min(yminlist)
  2914. for obj in obj_list:
  2915. obj.skew(num, 0, point=(xminimal, yminimal))
  2916. obj.plot()
  2917. self.object_changed.emit(obj)
  2918. def on_skewy(self):
  2919. obj_list = self.collection.get_selected()
  2920. xminlist = []
  2921. yminlist = []
  2922. if not obj_list:
  2923. self.inform.emit("[warning_notcl] No object selected.")
  2924. msg = "Please Select an object to skew/shear!"
  2925. warningbox = QtWidgets.QMessageBox()
  2926. warningbox.setText(msg)
  2927. warningbox.setWindowTitle("Warning ...")
  2928. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2929. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2930. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2931. warningbox.exec_()
  2932. else:
  2933. skewybox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  2934. min=-360, max=360, decimals=3)
  2935. num, ok = skewybox.get_value()
  2936. if ok:
  2937. # first get a bounding box to fit all
  2938. for obj in obj_list:
  2939. xmin, ymin, xmax, ymax = obj.bounds()
  2940. xminlist.append(xmin)
  2941. yminlist.append(ymin)
  2942. # get the minimum x,y and maximum x,y for all objects selected
  2943. xminimal = min(xminlist)
  2944. yminimal = min(yminlist)
  2945. for obj in obj_list:
  2946. obj.skew(0, num, point=(xminimal, yminimal))
  2947. obj.plot()
  2948. self.object_changed.emit(obj)
  2949. def delete_first_selected(self):
  2950. # Keep this for later
  2951. try:
  2952. name = self.collection.get_active().options["name"]
  2953. except AttributeError:
  2954. self.log.debug("Nothing selected for deletion")
  2955. return
  2956. # Remove plot
  2957. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  2958. # self.plotcanvas.auto_adjust_axes()
  2959. # Clear form
  2960. self.setup_component_editor()
  2961. # Remove from dictionary
  2962. self.collection.delete_active()
  2963. self.inform.emit("Object deleted: %s" % name)
  2964. def on_plots_updated(self):
  2965. """
  2966. Callback used to report when the plots have changed.
  2967. Adjust axes and zooms to fit.
  2968. :return: None
  2969. """
  2970. # self.plotcanvas.auto_adjust_axes()
  2971. self.plotcanvas.vispy_canvas.update() # TODO: Need update canvas?
  2972. self.on_zoom_fit(None)
  2973. # TODO: Rework toolbar 'clear', 'replot' functions
  2974. def on_toolbar_replot(self):
  2975. """
  2976. Callback for toolbar button. Re-plots all objects.
  2977. :return: None
  2978. """
  2979. self.report_usage("on_toolbar_replot")
  2980. self.log.debug("on_toolbar_replot()")
  2981. try:
  2982. self.collection.get_active().read_form()
  2983. except AttributeError:
  2984. self.log.debug("on_toolbar_replot(): AttributeError")
  2985. pass
  2986. self.plot_all()
  2987. def on_row_activated(self, index):
  2988. if index.isValid():
  2989. if index.internalPointer().parent_item != self.collection.root_item:
  2990. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2991. def on_zoom_fit(self, event):
  2992. """
  2993. Callback for zoom-out request. This can be either from the corresponding
  2994. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  2995. with axes limits from the geometry bounds of all objects.
  2996. :param event: Ignored.
  2997. :return: None
  2998. """
  2999. self.plotcanvas.fit_view()
  3000. def grid_status(self):
  3001. if self.ui.grid_snap_btn.isChecked():
  3002. return 1
  3003. else:
  3004. return 0
  3005. def on_key_over_plot(self, event):
  3006. """
  3007. Callback for the key pressed event when the canvas is focused. Keyboard
  3008. shortcuts are handled here. So far, these are the shortcuts:
  3009. ========== ============================================
  3010. Key Action
  3011. ========== ============================================
  3012. '1' Zoom-fit. Fits the axes limits to the data.
  3013. '2' Zoom-out.
  3014. '3' Zoom-in.
  3015. 'ctrl+m' Toggle on-off the measuring tool.
  3016. ========== ============================================
  3017. :param event: Ignored.
  3018. :return: None
  3019. """
  3020. self.key_modifiers = QtWidgets.QApplication.keyboardModifiers()
  3021. if self.key_modifiers == QtCore.Qt.ControlModifier:
  3022. if event.key == 'A':
  3023. self.on_selectall()
  3024. if event.key == 'C':
  3025. self.on_copy_object()
  3026. if event.key == 'E':
  3027. self.on_fileopenexcellon()
  3028. if event.key == 'G':
  3029. self.on_fileopengerber()
  3030. if event.key == 'N':
  3031. self.on_file_new_click()
  3032. if event.key == 'M':
  3033. self.measurement_tool.run()
  3034. if event.key == 'O':
  3035. self.on_file_openproject()
  3036. if event.key == 'S':
  3037. self.on_file_saveproject()
  3038. return
  3039. elif self.key_modifiers == QtCore.Qt.AltModifier:
  3040. # place holder for further shortcut key
  3041. if event.key == 'C':
  3042. self.calculator_tool.run()
  3043. if event.key == 'D':
  3044. self.dblsidedtool.run()
  3045. if event.key == 'L':
  3046. self.film_tool.run()
  3047. if event.key == 'N':
  3048. self.ncclear_tool.run()
  3049. if event.key == 'P':
  3050. self.paint_tool.run()
  3051. if event.key == 'R':
  3052. self.transform_tool.run()
  3053. if event.key == 'U':
  3054. self.cutout_tool.run()
  3055. if event.key == 'Z':
  3056. self.panelize_tool.run()
  3057. elif self.key_modifiers == QtCore.Qt.ShiftModifier:
  3058. # place holder for further shortcut key
  3059. if event.key == 'C':
  3060. self.on_copy_name()
  3061. # Toggle axis
  3062. if event.key == 'G':
  3063. self.on_toggle_axis()
  3064. # Open Preferences Window
  3065. if event.key == 'P':
  3066. self.on_preferences()
  3067. # Rotate Object by 90 degree CCW
  3068. if event.key == 'R':
  3069. self.on_rotate(silent=True, preset=-90)
  3070. # Run a Script
  3071. if event.key == 'S':
  3072. self.on_filerunscript()
  3073. # Toggle Workspace
  3074. if event.key == 'W':
  3075. self.on_workspace_menu()
  3076. # Skew on X axis
  3077. if event.key == 'X':
  3078. self.on_skewx()
  3079. # Skew on Y axis
  3080. if event.key == 'Y':
  3081. self.on_skewy()
  3082. return
  3083. else:
  3084. if event.key == self.defaults['fit_key']: # 1
  3085. self.on_zoom_fit(None)
  3086. return
  3087. if event.key == self.defaults['zoom_out_key']: # 2
  3088. self.plotcanvas.zoom(1 / self.defaults['zoom_ratio'], self.mouse)
  3089. return
  3090. if event.key == self.defaults['zoom_in_key']: # 3
  3091. self.plotcanvas.zoom(self.defaults['zoom_ratio'], self.mouse)
  3092. return
  3093. if event.key == 'Delete':
  3094. self.on_delete()
  3095. return
  3096. if event.key == 'Space':
  3097. if self.collection.get_active() is not None:
  3098. self.collection.get_active().ui.plot_cb.toggle()
  3099. self.delete_selection_shape()
  3100. if event.key == 'E':
  3101. self.object2editor()
  3102. if event.key == self.defaults['grid_toggle_key']: # G
  3103. self.ui.grid_snap_btn.trigger()
  3104. if event.key == 'J':
  3105. self.on_jump_to()
  3106. if event.key == 'L':
  3107. self.new_excellon_object()
  3108. if event.key == 'M':
  3109. self.move_tool.toggle()
  3110. return
  3111. if event.key == 'N':
  3112. self.on_new_geometry()
  3113. if event.key == 'O':
  3114. self.on_set_origin()
  3115. if event.key == 'P':
  3116. self.properties_tool.run()
  3117. if event.key == 'Q':
  3118. self.on_toggle_units_click()
  3119. if event.key == 'R':
  3120. self.on_rotate(silent=True, preset=90)
  3121. if event.key == 'S':
  3122. self.on_toggle_shell()
  3123. if event.key == 'V':
  3124. self.on_zoom_fit(None)
  3125. if event.key == 'X':
  3126. self.on_flipx()
  3127. if event.key == 'Y':
  3128. self.on_flipy()
  3129. if event.key == '`':
  3130. self.on_shortcut_list()
  3131. def on_key_release_over_plot(self, event):
  3132. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3133. if modifiers == QtCore.Qt.ControlModifier:
  3134. return
  3135. elif modifiers == QtCore.Qt.AltModifier:
  3136. # place holder for further shortcut key
  3137. return
  3138. elif modifiers == QtCore.Qt.ShiftModifier:
  3139. # place holder for further shortcut key
  3140. return
  3141. else:
  3142. return
  3143. def on_shortcut_list(self):
  3144. msg = '''<b>Shortcut list</b><br>
  3145. <br>
  3146. <b>~:</b> Show Shortcut List<br>
  3147. <br>
  3148. <b>1:</b> Zoom Fit<br>
  3149. <b>2:</b> Zoom Out<br>
  3150. <b>3:</b> Zoom In<br>
  3151. <b>A:</b> Draw an Arc (when in Edit Mode)<br>
  3152. <b>C:</b> Copy Geo Item (when in Edit Mode)<br>
  3153. <b>E:</b> Edit Object (if selected)<br>
  3154. <b>G:</b> Grid On/Off<br>
  3155. <b>J:</b> Jump to Coordinates<br>
  3156. <b>L:</b> New Excellon<br>
  3157. <b>M:</b> Move Obj<br>
  3158. <b>M:</b> Move Geo Item (when in Edit Mode)<br>
  3159. <b>N:</b> New Geometry<br>
  3160. <b>N:</b> Draw a Polygon (when in Edit Mode)<br>
  3161. <b>O:</b> Set Origin<br>
  3162. <b>O:</b> Draw a Circle (when in Edit Mode)<br>
  3163. <b>Q:</b> Change Units<br>
  3164. <b>P:</b> Open Properties Tool<br>
  3165. <b>P:</b> Draw a Path (when in Edit Mode)<br>
  3166. <b>R:</b> Rotate by 90 degree CW<br>
  3167. <b>R:</b> Draw Rectangle (when in Edit Mode)<br>
  3168. <b>S:</b> Shell Toggle<br>
  3169. <b>V:</b> View Fit<br>
  3170. <b>X:</b> Flip on X_axis<br>
  3171. <b>Y:</b> Flip on Y_axis<br>
  3172. <br>
  3173. <b>Space:</b> En(Dis)able Obj Plot<br>
  3174. <b>CTRL+A:</b> Select All<br>
  3175. <b>CTRL+C:</b> Copy Obj<br>
  3176. <b>CTRL+E:</b> Open Excellon File<br>
  3177. <b>CTRL+G:</b> Open Gerber File<br>
  3178. <b>CTRL+N:</b> New Project<br>
  3179. <b>CTRL+M:</b> Measurement Tool<br>
  3180. <b>CTRL+O:</b> Open Project<br>
  3181. <b>CTRL+S:</b> Save Project As<br>
  3182. <b>CTRL+S:</b> Save Object and Exit Editor (when in Edit Mode)<br>
  3183. <br>
  3184. <b>SHIFT+C:</b> Copy Obj_Name<br>
  3185. <b>SHIFT+G:</b> Toggle the axis<br>
  3186. <b>SHIFT+P:</b> Open Preferences Window<br>
  3187. <b>SHIFT+R:</b> Rotate by 90 degree CCW<br>
  3188. <b>SHIFT+S:</b> Run a Script<br>
  3189. <b>SHIFT+W:</b> Toggle the workspace<br>
  3190. <b>SHIFT+X:</b> Skew on X axis<br>
  3191. <b>SHIFT+Y:</b> Skew on Y axis<br>
  3192. <br>
  3193. <b>ALT+C:</b> Calculators Tool<br>
  3194. <b>ALT+D:</b> 2-Sided PCB Tool<br>
  3195. <b>ALT+L:</b> Film PCB Tool<br>
  3196. <b>ALT+N:</b> Non-Copper Clearing Tool<br>
  3197. <b>ALT+P:</b> Paint Area Tool<br>
  3198. <b>ALT+R:</b> Transformation Tool<br>
  3199. <b>ALT+U:</b> Cutout PCB Tool<br>
  3200. <b>ALT+Z:</b> Panelize PCB Tool<br>
  3201. <b>Del:</b> Delete Obj'''
  3202. helpbox = QtWidgets.QMessageBox()
  3203. helpbox.setText(msg)
  3204. helpbox.setWindowTitle("Help")
  3205. helpbox.setWindowIcon(QtGui.QIcon('share/help.png'))
  3206. helpbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3207. helpbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3208. helpbox.exec_()
  3209. def on_copy_name(self):
  3210. obj = self.collection.get_active()
  3211. try:
  3212. name = obj.options["name"]
  3213. except AttributeError:
  3214. log.debug("on_copy_name() --> No object selected to copy it's name")
  3215. self.inform.emit("[warning_notcl]No object selected to copy it's name")
  3216. return
  3217. self.clipboard.setText(name)
  3218. self.inform.emit("Name copied on clipboard ...")
  3219. def on_mouse_click_over_plot(self, event):
  3220. """
  3221. Callback for the mouse click event over the plot. This event is generated
  3222. by the Matplotlib backend and has been registered in ``self.__init__()``.
  3223. For details, see: http://matplotlib.org/users/event_handling.html
  3224. Default actions are:
  3225. * Copy coordinates to clipboard. Ex.: (65.5473, -13.2679)
  3226. :param event: Contains information about the event, like which button
  3227. was clicked, the pixel coordinates and the axes coordinates.
  3228. :return: None
  3229. """
  3230. self.pos = []
  3231. # So it can receive key presses
  3232. self.plotcanvas.vispy_canvas.native.setFocus()
  3233. # Set the mouse button for panning
  3234. self.plotcanvas.vispy_canvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  3235. self.pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3236. if self.grid_status() == True:
  3237. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  3238. self.app_cursor.enabled = True
  3239. else:
  3240. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  3241. self.app_cursor.enabled = False
  3242. try:
  3243. App.log.debug('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (
  3244. event.button, event.pos[0], event.pos[1], self.pos[0], self.pos[1]))
  3245. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3246. if event.button == 1:
  3247. # Reset here the relative coordinates so there is a new reference on the click position
  3248. if self.rel_point1 is None:
  3249. self.rel_point1 = self.pos
  3250. else:
  3251. self.rel_point2 = copy(self.rel_point1)
  3252. self.rel_point1 = self.pos
  3253. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  3254. if modifiers == QtCore.Qt.ShiftModifier:
  3255. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  3256. return
  3257. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will deselect,
  3258. # and if it's not selected then it will be selected
  3259. if modifiers == QtCore.Qt.ControlModifier:
  3260. # If there is no active command (self.command_active is None) then we check if we clicked on
  3261. # a object by checking the bounding limits against mouse click position
  3262. if self.command_active is None:
  3263. self.select_objects(key='CTRL')
  3264. else:
  3265. # If there is no active command (self.command_active is None) then we check if we clicked on a object by
  3266. # checking the bounding limits against mouse click position
  3267. if self.command_active is None:
  3268. self.select_objects()
  3269. self.on_mouse_move_over_plot(event, origin_click=True)
  3270. except Exception as e:
  3271. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  3272. def on_double_click_over_plot(self, event):
  3273. # make double click work only for the LMB
  3274. if event.button == 1:
  3275. if not self.collection.get_selected():
  3276. pass
  3277. else:
  3278. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3279. #delete the selection shape(S) as it may be in the way
  3280. self.delete_selection_shape()
  3281. def on_mouse_move_over_plot(self, event, origin_click=None):
  3282. """
  3283. Callback for the mouse motion event over the plot. This event is generated
  3284. by the Matplotlib backend and has been registered in ``self.__init__()``.
  3285. For details, see: http://matplotlib.org/users/event_handling.html
  3286. :param event: Contains information about the event.
  3287. :param origin_click
  3288. :return: None
  3289. """
  3290. # So it can receive key presses
  3291. self.plotcanvas.vispy_canvas.native.setFocus()
  3292. self.pos_jump = event.pos
  3293. if origin_click is True:
  3294. pass
  3295. else:
  3296. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  3297. if event.button == 2:
  3298. self.panning_action = True
  3299. return
  3300. else:
  3301. self.panning_action = False
  3302. if self.rel_point1 is not None:
  3303. try: # May fail in case mouse not within axes
  3304. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3305. if self.grid_status():
  3306. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3307. self.app_cursor.enabled = True
  3308. # Update cursor
  3309. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  3310. else:
  3311. pos = (pos_canvas[0], pos_canvas[1])
  3312. self.app_cursor.enabled = False
  3313. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3314. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  3315. dx = pos[0] - self.rel_point1[0]
  3316. dy = pos[1] - self.rel_point1[1]
  3317. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3318. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3319. self.mouse = [pos[0], pos[1]]
  3320. # if the mouse is moved and the LMB is clicked then the action is a selection
  3321. if event.is_dragging == 1 and event.button == 1:
  3322. self.delete_selection_shape()
  3323. if dx < 0:
  3324. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  3325. face_color=self.defaults['global_alt_sel_fill'])
  3326. self.selection_type = False
  3327. else:
  3328. self.draw_moving_selection_shape(self.pos, pos)
  3329. self.selection_type = True
  3330. # delete the status message on mouse move
  3331. # self.inform.emit("")
  3332. except:
  3333. self.ui.position_label.setText("")
  3334. self.ui.rel_position_label.setText("")
  3335. self.mouse = None
  3336. def on_mouse_click_release_over_plot(self, event):
  3337. """
  3338. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  3339. and has been registered in ''self.__init__()''.
  3340. :param event: contains information about the event.
  3341. :return:
  3342. """
  3343. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3344. if self.grid_status():
  3345. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3346. else:
  3347. pos = (pos_canvas[0], pos_canvas[1])
  3348. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  3349. # canvas menu
  3350. try:
  3351. if event.button == 2: # right click
  3352. if self.panning_action is True:
  3353. self.panning_action = False
  3354. else:
  3355. self.cursor = QtGui.QCursor()
  3356. self.ui.popMenu.popup(self.cursor.pos())
  3357. except Exception as e:
  3358. log.warning("Error: %s" % str(e))
  3359. return
  3360. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  3361. # selection and then select a type of selection ("enclosing" or "touching")
  3362. try:
  3363. if event.button == 1: # left click
  3364. if self.selection_type is not None:
  3365. self.selection_area_handler(self.pos, pos, self.selection_type)
  3366. self.selection_type = None
  3367. except Exception as e:
  3368. log.warning("Error: %s" % str(e))
  3369. return
  3370. def selection_area_handler(self, start_pos, end_pos, sel_type):
  3371. """
  3372. :param start_pos: mouse position when the selection LMB click was done
  3373. :param end_pos: mouse position when the left mouse button is released
  3374. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  3375. :return:
  3376. """
  3377. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  3378. self.delete_selection_shape()
  3379. for obj in self.collection.get_list():
  3380. try:
  3381. # select the object(s) only if it is enabled (plotted)
  3382. if obj.options['plot']:
  3383. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']), (obj.options['xmax'], obj.options['ymin']),
  3384. (obj.options['xmax'], obj.options['ymax']), (obj.options['xmin'], obj.options['ymax'])])
  3385. if sel_type is True:
  3386. if poly_obj.within(poly_selection):
  3387. # create the selection box around the selected object
  3388. self.draw_selection_shape(obj)
  3389. self.collection.set_active(obj.options['name'])
  3390. else:
  3391. if poly_selection.intersects(poly_obj):
  3392. # create the selection box around the selected object
  3393. self.draw_selection_shape(obj)
  3394. self.collection.set_active(obj.options['name'])
  3395. except:
  3396. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  3397. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  3398. # In this case poly_obj creation (see above) will fail
  3399. pass
  3400. def select_objects(self, key=None):
  3401. # list where we store the overlapped objects under our mouse left click position
  3402. objects_under_the_click_list = []
  3403. # Populate the list with the overlapped objects on the click position
  3404. curr_x, curr_y = self.pos
  3405. for obj in self.all_objects_list:
  3406. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  3407. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  3408. if obj.options['name'] not in objects_under_the_click_list:
  3409. if obj.options['plot']:
  3410. # add objects to the objects_under_the_click list only if the object is plotted
  3411. # (active and not disabled)
  3412. objects_under_the_click_list.append(obj.options['name'])
  3413. try:
  3414. # If there is no element in the overlapped objects list then make everyone inactive
  3415. # because we selected "nothing"
  3416. if not objects_under_the_click_list:
  3417. self.collection.set_all_inactive()
  3418. # delete the possible selection box around a possible selected object
  3419. self.delete_selection_shape()
  3420. # and as a convenience move the focus to the Project tab because Selected tab is now empty
  3421. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3422. else:
  3423. # case when there is only an object under the click and we toggle it
  3424. if len(objects_under_the_click_list) == 1:
  3425. if self.collection.get_active() is None :
  3426. self.collection.set_active(objects_under_the_click_list[0])
  3427. # create the selection box around the selected object
  3428. curr_sel_obj = self.collection.get_active()
  3429. self.draw_selection_shape(curr_sel_obj)
  3430. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  3431. self.collection.set_all_inactive()
  3432. self.delete_selection_shape()
  3433. self.collection.set_active(objects_under_the_click_list[0])
  3434. # create the selection box around the selected object
  3435. curr_sel_obj = self.collection.get_active()
  3436. self.draw_selection_shape(curr_sel_obj)
  3437. else:
  3438. self.collection.set_all_inactive()
  3439. self.delete_selection_shape()
  3440. else:
  3441. # If there is no selected object
  3442. # make active the first element of the overlapped objects list
  3443. if self.collection.get_active() is None:
  3444. self.collection.set_active(objects_under_the_click_list[0])
  3445. name_sel_obj = self.collection.get_active().options['name']
  3446. # In case that there is a selected object but it is not in the overlapped object list
  3447. # make that object inactive and activate the first element in the overlapped object list
  3448. if name_sel_obj not in objects_under_the_click_list:
  3449. self.collection.set_inactive(name_sel_obj)
  3450. name_sel_obj = objects_under_the_click_list[0]
  3451. self.collection.set_active(name_sel_obj)
  3452. else:
  3453. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  3454. self.collection.set_all_inactive()
  3455. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) % len(objects_under_the_click_list)])
  3456. curr_sel_obj = self.collection.get_active()
  3457. # delete the possible selection box around a possible selected object
  3458. self.delete_selection_shape()
  3459. # create the selection box around the selected object
  3460. self.draw_selection_shape(curr_sel_obj)
  3461. # for obj in self.collection.get_list():
  3462. # obj.plot()
  3463. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  3464. # TODO: on selected objects change the object colors and do not draw the selection box
  3465. # self.plotcanvas.vispy_canvas.update() # this updates the canvas
  3466. except Exception as e:
  3467. log.error("[error] Something went bad. %s" % str(e))
  3468. return
  3469. def delete_selection_shape(self):
  3470. self.move_tool.sel_shapes.clear()
  3471. self.move_tool.sel_shapes.redraw()
  3472. def draw_selection_shape(self, sel_obj):
  3473. """
  3474. :param sel_obj: the object for which the selection shape must be drawn
  3475. :return:
  3476. """
  3477. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  3478. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  3479. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  3480. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  3481. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  3482. #blue_t = Color('blue')
  3483. blue_t = Color(self.defaults['global_sel_fill'])
  3484. blue_t.alpha = 0.3
  3485. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect, color=self.defaults['global_sel_line'],
  3486. face_color=blue_t, update=True, layer=0, tolerance=None))
  3487. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  3488. """
  3489. :param old_coords: old coordinates
  3490. :param coords: new coordinates
  3491. :return:
  3492. """
  3493. if 'color' in kwargs:
  3494. color = kwargs['color']
  3495. else:
  3496. color = self.defaults['global_sel_line']
  3497. if 'face_color' in kwargs:
  3498. face_color = kwargs['face_color']
  3499. else:
  3500. face_color = self.defaults['global_sel_fill']
  3501. x0, y0 = old_coords
  3502. x1, y1 = coords
  3503. pt1 = (x0, y0)
  3504. pt2 = (x1, y0)
  3505. pt3 = (x1, y1)
  3506. pt4 = (x0, y1)
  3507. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  3508. color_t = Color(face_color)
  3509. color_t.alpha = 0.3
  3510. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  3511. layer=0, tolerance=None)
  3512. def on_file_new_click(self):
  3513. if self.collection.get_list():
  3514. msgbox = QtWidgets.QMessageBox()
  3515. # msgbox.setText("<B>Save changes ...</B>")
  3516. msgbox.setText("There are files/objects opened in FlatCAM.\n"
  3517. "Creating a New project will delete them.\n"
  3518. "Do you want to Save the project?")
  3519. msgbox.setWindowTitle("Save changes")
  3520. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3521. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Yes |
  3522. QtWidgets.QMessageBox.No)
  3523. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3524. response = msgbox.exec_()
  3525. if response == QtWidgets.QMessageBox.Yes:
  3526. self.on_file_saveprojectas()
  3527. elif response == QtWidgets.QMessageBox.Cancel:
  3528. return
  3529. self.on_file_new()
  3530. else:
  3531. self.on_file_new()
  3532. self.inform.emit("[success] New Project created...")
  3533. def on_file_new(self):
  3534. """
  3535. Callback for menu item File->New. Returns the application to its
  3536. startup state. This method is thread-safe.
  3537. :return: None
  3538. """
  3539. self.report_usage("on_file_new")
  3540. # Remove everything from memory
  3541. App.log.debug("on_file_new()")
  3542. # Clear pool
  3543. self.clear_pool()
  3544. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  3545. self.init_tcl()
  3546. self.delete_selection_shape()
  3547. self.collection.delete_all()
  3548. self.setup_component_editor()
  3549. # Clear project filename
  3550. self.project_filename = None
  3551. # Load the application defaults
  3552. self.load_defaults(filename='current_defaults')
  3553. # Re-fresh project options
  3554. self.on_options_app2project()
  3555. # Init Tools
  3556. self.init_tools()
  3557. # take the focus of the Notebook on Project Tab.
  3558. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3559. def obj_properties(self):
  3560. self.properties_tool.run()
  3561. def obj_move(self):
  3562. self.move_tool.run()
  3563. def on_fileopengerber(self):
  3564. """
  3565. File menu callback for opening a Gerber.
  3566. :return: None
  3567. """
  3568. self.report_usage("on_fileopengerber")
  3569. App.log.debug("on_fileopengerber()")
  3570. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  3571. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  3572. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  3573. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  3574. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  3575. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  3576. "Allegro Files (*.art);;" \
  3577. "Mentor Files (*.pho *.gdo);;" \
  3578. "All Files (*.*)"
  3579. try:
  3580. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Gerber",
  3581. directory=self.get_last_folder(), filter=_filter_)
  3582. except TypeError:
  3583. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Gerber", filter=_filter_)
  3584. filenames = [str(filename) for filename in filenames]
  3585. if len(filenames) == 0:
  3586. self.inform.emit("[warning_notcl]Open Gerber cancelled.")
  3587. else:
  3588. for filename in filenames:
  3589. if filename != '':
  3590. self.worker_task.emit({'fcn': self.open_gerber,
  3591. 'params': [filename]})
  3592. def on_fileopengerber_follow(self):
  3593. """
  3594. File menu callback for opening a Gerber.
  3595. :return: None
  3596. """
  3597. self.report_usage("on_fileopengerber_follow")
  3598. App.log.debug("on_fileopengerber_follow()")
  3599. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  3600. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  3601. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  3602. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  3603. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  3604. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  3605. "Allegro Files (*.art);;" \
  3606. "Mentor Files (*.pho *.gdo);;" \
  3607. "All Files (*.*)"
  3608. try:
  3609. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Gerber with Follow",
  3610. directory=self.get_last_folder(), filter=_filter_)
  3611. except TypeError:
  3612. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Gerber with Follow", filter=_filter_)
  3613. # The Qt methods above will return a QString which can cause problems later.
  3614. # So far json.dump() will fail to serialize it.
  3615. # TODO: Improve the serialization methods and remove this fix.
  3616. filename = str(filename)
  3617. follow = True
  3618. if filename == "":
  3619. self.inform.emit("[warning_notcl]Open Gerber-Follow cancelled.")
  3620. else:
  3621. self.worker_task.emit({'fcn': self.open_gerber,
  3622. 'params': [filename, follow]})
  3623. def on_fileopenexcellon(self):
  3624. """
  3625. File menu callback for opening an Excellon file.
  3626. :return: None
  3627. """
  3628. self.report_usage("on_fileopenexcellon")
  3629. App.log.debug("on_fileopenexcellon()")
  3630. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc);;" \
  3631. "All Files (*.*)"
  3632. try:
  3633. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Excellon",
  3634. directory=self.get_last_folder(), filter=_filter_)
  3635. except TypeError:
  3636. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Excellon", filter=_filter_)
  3637. filenames = [str(filename) for filename in filenames]
  3638. if len(filenames) == 0:
  3639. self.inform.emit("[warning_notcl]Open Excellon cancelled.")
  3640. else:
  3641. for filename in filenames:
  3642. if filename != '':
  3643. self.worker_task.emit({'fcn': self.open_excellon,
  3644. 'params': [filename]})
  3645. def on_fileopengcode(self):
  3646. """
  3647. File menu call back for opening gcode.
  3648. :return: None
  3649. """
  3650. self.report_usage("on_fileopengcode")
  3651. App.log.debug("on_fileopengcode()")
  3652. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  3653. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  3654. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  3655. "All Files (*.*)"
  3656. try:
  3657. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open G-Code",
  3658. directory=self.get_last_folder(), filter=_filter_)
  3659. except TypeError:
  3660. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open G-Code", filter=_filter_)
  3661. filenames = [str(filename) for filename in filenames]
  3662. if len(filenames) == 0:
  3663. self.inform.emit("[warning_notcl]Open G-Code cancelled.")
  3664. else:
  3665. for filename in filenames:
  3666. if filename != '':
  3667. self.worker_task.emit({'fcn': self.open_gcode,
  3668. 'params': [filename]})
  3669. def on_file_openproject(self):
  3670. """
  3671. File menu callback for opening a project.
  3672. :return: None
  3673. """
  3674. self.report_usage("on_file_openproject")
  3675. App.log.debug("on_file_openproject()")
  3676. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  3677. try:
  3678. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Project",
  3679. directory=self.get_last_folder(), filter=_filter_)
  3680. except TypeError:
  3681. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Project", filter = _filter_)
  3682. # The Qt methods above will return a QString which can cause problems later.
  3683. # So far json.dump() will fail to serialize it.
  3684. # TODO: Improve the serialization methods and remove this fix.
  3685. filename = str(filename)
  3686. if filename == "":
  3687. self.inform.emit("[warning_notcl]Open Project cancelled.")
  3688. else:
  3689. # self.worker_task.emit({'fcn': self.open_project,
  3690. # 'params': [filename]})
  3691. # The above was failing because open_project() is not
  3692. # thread safe. The new_project()
  3693. self.open_project(filename)
  3694. def on_file_exportsvg(self):
  3695. """
  3696. Callback for menu item File->Export SVG.
  3697. :return: None
  3698. """
  3699. self.report_usage("on_file_exportsvg")
  3700. App.log.debug("on_file_exportsvg()")
  3701. obj = self.collection.get_active()
  3702. if obj is None:
  3703. self.inform.emit("WARNING: No object selected.")
  3704. msg = "Please Select a Geometry object to export"
  3705. msgbox = QtWidgets.QMessageBox()
  3706. msgbox.setInformativeText(msg)
  3707. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3708. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3709. msgbox.exec_()
  3710. return
  3711. # Check for more compatible types and add as required
  3712. if (not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMCNCjob)
  3713. and not isinstance(obj, FlatCAMExcellon)):
  3714. msg = "[error_notcl] Only Geometry, Gerber and CNCJob objects can be used."
  3715. msgbox = QtWidgets.QMessageBox()
  3716. msgbox.setInformativeText(msg)
  3717. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3718. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3719. msgbox.exec_()
  3720. return
  3721. name = self.collection.get_active().options["name"]
  3722. filter = "SVG File (*.svg);;All Files (*.*)"
  3723. try:
  3724. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export SVG",
  3725. directory=self.get_last_save_folder(), filter=filter)
  3726. except TypeError:
  3727. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export SVG", filter=filter)
  3728. filename = str(filename)
  3729. if filename == "":
  3730. self.inform.emit("[warning_notcl]Export SVG cancelled.")
  3731. return
  3732. else:
  3733. self.export_svg(name, filename)
  3734. self.file_saved.emit("SVG", filename)
  3735. def on_file_exportpng(self):
  3736. self.report_usage("on_file_exportpng")
  3737. App.log.debug("on_file_exportpng()")
  3738. image = _screenshot()
  3739. data = np.asarray(image)
  3740. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  3741. self.inform.emit('[[warning_notcl]] Data must be a 3D array with last dimension 3 or 4')
  3742. return
  3743. filter = "PNG File (*.png);;All Files (*.*)"
  3744. try:
  3745. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export PNG Image",
  3746. directory=self.get_last_save_folder(), filter=filter)
  3747. except TypeError:
  3748. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export PNG Image", filter=filter)
  3749. filename = str(filename)
  3750. if filename == "":
  3751. self.inform.emit("Export PNG cancelled.")
  3752. return
  3753. else:
  3754. write_png(filename, data)
  3755. self.file_saved.emit("png", filename)
  3756. def on_file_exportexcellon(self, altium_format=None):
  3757. """
  3758. Callback for menu item File->Export SVG.
  3759. :return: None
  3760. """
  3761. self.report_usage("on_file_exportexcellon")
  3762. App.log.debug("on_file_exportexcellon()")
  3763. obj = self.collection.get_active()
  3764. if obj is None:
  3765. self.inform.emit("[warning_notcl] No object selected.")
  3766. msg = "Please Select an Excellon object to export"
  3767. msgbox = QtWidgets.QMessageBox()
  3768. msgbox.setInformativeText(msg)
  3769. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3770. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3771. msgbox.exec_()
  3772. return
  3773. # Check for more compatible types and add as required
  3774. if not isinstance(obj, FlatCAMExcellon):
  3775. msg = "[warning_notcl] Only Excellon objects can be used."
  3776. msgbox = QtWidgets.QMessageBox()
  3777. msgbox.setInformativeText(msg)
  3778. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3779. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3780. msgbox.exec_()
  3781. return
  3782. name = self.collection.get_active().options["name"]
  3783. filter = "Excellon File (*.drl);;Excellon File (*.txt);;All Files (*.*)"
  3784. try:
  3785. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export Excellon",
  3786. directory=self.get_last_save_folder(), filter=filter)
  3787. except TypeError:
  3788. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export Excellon", filter=filter)
  3789. filename = str(filename)
  3790. if filename == "":
  3791. self.inform.emit("[warning_notcl]Export Excellon cancelled.")
  3792. return
  3793. else:
  3794. if altium_format == None:
  3795. self.export_excellon(name, filename)
  3796. self.file_saved.emit("Excellon", filename)
  3797. else:
  3798. self.export_excellon(name, filename, altium_format=True)
  3799. self.file_saved.emit("Excellon", filename)
  3800. def on_file_exportdxf(self):
  3801. """
  3802. Callback for menu item File->Export DXF.
  3803. :return: None
  3804. """
  3805. self.report_usage("on_file_exportdxf")
  3806. App.log.debug("on_file_exportdxf()")
  3807. obj = self.collection.get_active()
  3808. if obj is None:
  3809. self.inform.emit("W[warning_notcl] No object selected.")
  3810. msg = "Please Select a Geometry object to export"
  3811. msgbox = QtWidgets.QMessageBox()
  3812. msgbox.setInformativeText(msg)
  3813. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3814. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3815. msgbox.exec_()
  3816. return
  3817. # Check for more compatible types and add as required
  3818. if not isinstance(obj, FlatCAMGeometry):
  3819. msg = "[error_notcl] Only Geometry objects can be used."
  3820. msgbox = QtWidgets.QMessageBox()
  3821. msgbox.setInformativeText(msg)
  3822. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3823. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3824. msgbox.exec_()
  3825. return
  3826. name = self.collection.get_active().options["name"]
  3827. filter = "DXF File (*.DXF);;All Files (*.*)"
  3828. try:
  3829. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export DXF",
  3830. directory=self.get_last_save_folder(), filter=filter)
  3831. except TypeError:
  3832. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export DXF", filter=filter)
  3833. filename = str(filename)
  3834. if filename == "":
  3835. self.inform.emit("[warning_notcl]Export DXF cancelled.")
  3836. return
  3837. else:
  3838. self.export_dxf(name, filename)
  3839. self.file_saved.emit("DXF", filename)
  3840. def on_file_importsvg(self, type_of_obj):
  3841. """
  3842. Callback for menu item File->Import SVG.
  3843. :param type_of_obj: to import the SVG as Geometry or as Gerber
  3844. :type type_of_obj: str
  3845. :return: None
  3846. """
  3847. self.report_usage("on_file_importsvg")
  3848. App.log.debug("on_file_importsvg()")
  3849. filter = "SVG File (*.svg);;All Files (*.*)"
  3850. try:
  3851. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import SVG",
  3852. directory=self.get_last_folder(), filter=filter)
  3853. except TypeError:
  3854. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import SVG", filter=filter)
  3855. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  3856. type_of_obj = "geometry"
  3857. filenames = [str(filename) for filename in filenames]
  3858. if len(filenames) == 0:
  3859. self.inform.emit("[warning_notcl]Open SVG cancelled.")
  3860. else:
  3861. for filename in filenames:
  3862. if filename != '':
  3863. self.worker_task.emit({'fcn': self.import_svg,
  3864. 'params': [filename, type_of_obj]})
  3865. def on_file_importdxf(self, type_of_obj):
  3866. """
  3867. Callback for menu item File->Import DXF.
  3868. :param type_of_obj: to import the DXF as Geometry or as Gerber
  3869. :type type_of_obj: str
  3870. :return: None
  3871. """
  3872. self.report_usage("on_file_importdxf")
  3873. App.log.debug("on_file_importdxf()")
  3874. filter = "DXF File (*.DXF);;All Files (*.*)"
  3875. try:
  3876. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import DXF",
  3877. directory=self.get_last_folder(), filter=filter)
  3878. except TypeError:
  3879. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import DXF", filter=filter)
  3880. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  3881. type_of_obj = "geometry"
  3882. filenames = [str(filename) for filename in filenames]
  3883. if len(filenames) == 0:
  3884. self.inform.emit("[warning_notcl]Open DXF cancelled.")
  3885. else:
  3886. for filename in filenames:
  3887. if filename != '':
  3888. self.worker_task.emit({'fcn': self.import_dxf,
  3889. 'params': [filename, type_of_obj]})
  3890. def on_filerunscript(self):
  3891. """
  3892. File menu callback for loading and running a TCL script.
  3893. :return: None
  3894. """
  3895. self.report_usage("on_filerunscript")
  3896. App.log.debug("on_file_runscript()")
  3897. _filter_ = "TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  3898. try:
  3899. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open TCL script",
  3900. directory=self.get_last_folder(), filter=_filter_)
  3901. except TypeError:
  3902. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open TCL script", filter=_filter_)
  3903. # The Qt methods above will return a QString which can cause problems later.
  3904. # So far json.dump() will fail to serialize it.
  3905. # TODO: Improve the serialization methods and remove this fix.
  3906. filename = str(filename)
  3907. if filename == "":
  3908. self.inform.emit("[warning_notcl]Open TCL script cancelled.")
  3909. else:
  3910. try:
  3911. with open(filename, "r") as tcl_script:
  3912. cmd_line_shellfile_content = tcl_script.read()
  3913. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  3914. except Exception as ext:
  3915. print("ERROR: ", ext)
  3916. sys.exit(2)
  3917. def on_file_saveproject(self):
  3918. """
  3919. Callback for menu item File->Save Project. Saves the project to
  3920. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  3921. if set to None. The project is saved by calling ``self.save_project()``.
  3922. :return: None
  3923. """
  3924. self.report_usage("on_file_saveproject")
  3925. if self.project_filename is None:
  3926. self.on_file_saveprojectas()
  3927. else:
  3928. self.worker_task.emit({'fcn': self.save_project,
  3929. 'params': [self.project_filename]})
  3930. # self.save_project(self.project_filename)
  3931. self.file_opened.emit("project", self.project_filename)
  3932. self.file_saved.emit("project", self.project_filename)
  3933. def on_file_saveprojectas(self, make_copy=False, thread=True):
  3934. """
  3935. Callback for menu item File->Save Project As... Opens a file
  3936. chooser and saves the project to the given file via
  3937. ``self.save_project()``.
  3938. :return: None
  3939. """
  3940. self.report_usage("on_file_saveprojectas")
  3941. filter = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  3942. try:
  3943. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Save Project As ...",
  3944. directory=self.get_last_save_folder(), filter=filter)
  3945. except TypeError:
  3946. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Save Project As ...", filter=filter)
  3947. filename = str(filename)
  3948. if filename == '':
  3949. self.inform.emit("[warning_notcl]Save Project cancelled.")
  3950. return
  3951. try:
  3952. f = open(filename, 'r')
  3953. f.close()
  3954. exists = True
  3955. except IOError:
  3956. exists = False
  3957. msg = "File exists. Overwrite?"
  3958. if exists:
  3959. msgbox = QtWidgets.QMessageBox()
  3960. msgbox.setInformativeText(msg)
  3961. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel |QtWidgets.QMessageBox.Ok)
  3962. msgbox.setDefaultButton(QtWidgets.QMessageBox.Cancel)
  3963. result = msgbox.exec_()
  3964. if result ==QtWidgets.QMessageBox.Cancel:
  3965. return
  3966. if thread is True:
  3967. self.worker_task.emit({'fcn': self.save_project,
  3968. 'params': [filename]})
  3969. else:
  3970. self.save_project(filename)
  3971. # self.save_project(filename)
  3972. self.file_opened.emit("project", filename)
  3973. self.file_saved.emit("project", filename)
  3974. if not make_copy:
  3975. self.project_filename = filename
  3976. def export_svg(self, obj_name, filename, scale_factor=0.00):
  3977. """
  3978. Exports a Geometry Object to an SVG file.
  3979. :param filename: Path to the SVG file to save to.
  3980. :return:
  3981. """
  3982. if filename is None:
  3983. filename = self.defaults["global_last_save_folder"]
  3984. self.log.debug("export_svg()")
  3985. try:
  3986. obj = self.collection.get_by_name(str(obj_name))
  3987. except:
  3988. # TODO: The return behavior has not been established... should raise exception?
  3989. return "Could not retrieve object: %s" % obj_name
  3990. with self.proc_container.new("Exporting SVG") as proc:
  3991. exported_svg = obj.export_svg(scale_factor=scale_factor)
  3992. # Determine bounding area for svg export
  3993. bounds = obj.bounds()
  3994. size = obj.size()
  3995. # Convert everything to strings for use in the xml doc
  3996. svgwidth = str(size[0])
  3997. svgheight = str(size[1])
  3998. minx = str(bounds[0])
  3999. miny = str(bounds[1] - size[1])
  4000. uom = obj.units.lower()
  4001. # Add a SVG Header and footer to the svg output from shapely
  4002. # The transform flips the Y Axis so that everything renders
  4003. # properly within svg apps such as inkscape
  4004. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4005. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4006. svg_header += 'width="' + svgwidth + uom + '" '
  4007. svg_header += 'height="' + svgheight + uom + '" '
  4008. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  4009. svg_header += '<g transform="scale(1,-1)">'
  4010. svg_footer = '</g> </svg>'
  4011. svg_elem = svg_header + exported_svg + svg_footer
  4012. # Parse the xml through a xml parser just to add line feeds
  4013. # and to make it look more pretty for the output
  4014. svgcode = parse_xml_string(svg_elem)
  4015. with open(filename, 'w') as fp:
  4016. fp.write(svgcode.toprettyxml())
  4017. self.file_saved.emit("SVG", filename)
  4018. self.inform.emit("[success] SVG file exported to " + filename)
  4019. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  4020. """
  4021. Exports a Geometry Object to an SVG file in negative.
  4022. :param filename: Path to the SVG file to save to.
  4023. :param: use_thread: If True use threads
  4024. :type: Bool
  4025. :return:
  4026. """
  4027. if filename is None:
  4028. filename = self.defaults["global_last_save_folder"]
  4029. self.log.debug("export_svg() negative")
  4030. try:
  4031. obj = self.collection.get_by_name(str(obj_name))
  4032. except:
  4033. # TODO: The return behavior has not been established... should raise exception?
  4034. return "Could not retrieve object: %s" % obj_name
  4035. try:
  4036. box = self.collection.get_by_name(str(box_name))
  4037. except:
  4038. # TODO: The return behavior has not been established... should raise exception?
  4039. return "Could not retrieve object: %s" % box_name
  4040. if box is None:
  4041. self.inform.emit("[warning_notcl]No object Box. Using instead %s" % obj)
  4042. box = obj
  4043. def make_negative_film():
  4044. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4045. self.progress.emit(40)
  4046. # Determine bounding area for svg export
  4047. bounds = box.bounds()
  4048. size = box.size()
  4049. uom = obj.units.lower()
  4050. # Convert everything to strings for use in the xml doc
  4051. svgwidth = str(size[0] + (2 * boundary))
  4052. svgheight = str(size[1] + (2 * boundary))
  4053. minx = str(bounds[0] - boundary)
  4054. miny = str(bounds[1] + boundary + size[1])
  4055. miny_rect = str(bounds[1] - boundary)
  4056. # Add a SVG Header and footer to the svg output from shapely
  4057. # The transform flips the Y Axis so that everything renders
  4058. # properly within svg apps such as inkscape
  4059. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4060. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4061. svg_header += 'width="' + svgwidth + uom + '" '
  4062. svg_header += 'height="' + svgheight + uom + '" '
  4063. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  4064. svg_header += '>'
  4065. svg_header += '<g transform="scale(1,-1)">'
  4066. svg_footer = '</g> </svg>'
  4067. self.progress.emit(60)
  4068. # Change the attributes of the exported SVG
  4069. # We don't need stroke-width - wrong, we do when we have lines with certain width
  4070. # We set opacity to maximum
  4071. # We set the color to WHITE
  4072. root = ET.fromstring(exported_svg)
  4073. for child in root:
  4074. child.set('fill', '#FFFFFF')
  4075. child.set('opacity', '1.0')
  4076. child.set('stroke', '#FFFFFF')
  4077. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  4078. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  4079. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  4080. first_svg_elem_tag = 'rect'
  4081. first_svg_elem_attribs = {
  4082. 'x': minx,
  4083. 'y': miny_rect,
  4084. 'width': svgwidth,
  4085. 'height': svgheight,
  4086. 'id': 'neg_rect',
  4087. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  4088. }
  4089. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  4090. exported_svg = ET.tostring(root)
  4091. svg_elem = svg_header + str(exported_svg) + svg_footer
  4092. self.progress.emit(80)
  4093. # Parse the xml through a xml parser just to add line feeds
  4094. # and to make it look more pretty for the output
  4095. doc = parse_xml_string(svg_elem)
  4096. with open(filename, 'w') as fp:
  4097. fp.write(doc.toprettyxml())
  4098. self.progress.emit(100)
  4099. self.file_saved.emit("SVG", filename)
  4100. self.inform.emit("[success] SVG file exported to " + filename)
  4101. if use_thread is True:
  4102. proc = self.proc_container.new("Generating Film ... Please wait.")
  4103. def job_thread_film(app_obj):
  4104. try:
  4105. make_negative_film()
  4106. except Exception as e:
  4107. proc.done()
  4108. return
  4109. proc.done()
  4110. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  4111. else:
  4112. make_negative_film()
  4113. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  4114. """
  4115. Exports a Geometry Object to an SVG file in negative.
  4116. :param filename: Path to the SVG file to save to.
  4117. :param: use_thread: If True use threads
  4118. :type: Bool
  4119. :return:
  4120. """
  4121. if filename is None:
  4122. filename = self.defaults["global_last_save_folder"]
  4123. self.log.debug("export_svg() black")
  4124. try:
  4125. obj = self.collection.get_by_name(str(obj_name))
  4126. except:
  4127. # TODO: The return behavior has not been established... should raise exception?
  4128. return "Could not retrieve object: %s" % obj_name
  4129. try:
  4130. box = self.collection.get_by_name(str(box_name))
  4131. except:
  4132. # TODO: The return behavior has not been established... should raise exception?
  4133. return "Could not retrieve object: %s" % box_name
  4134. if box is None:
  4135. self.inform.emit("[warning_notcl]No object Box. Using instead %s" % obj)
  4136. box = obj
  4137. def make_black_film():
  4138. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4139. self.progress.emit(40)
  4140. # Change the attributes of the exported SVG
  4141. # We don't need stroke-width
  4142. # We set opacity to maximum
  4143. # We set the colour to WHITE
  4144. root = ET.fromstring(exported_svg)
  4145. for child in root:
  4146. child.set('fill', '#000000')
  4147. child.set('opacity', '1.0')
  4148. child.set('stroke', '#000000')
  4149. exported_svg = ET.tostring(root)
  4150. # Determine bounding area for svg export
  4151. bounds = box.bounds()
  4152. size = box.size()
  4153. # This contain the measure units
  4154. uom = obj.units.lower()
  4155. # Define a boundary around SVG of about 1.0mm (~39mils)
  4156. if uom in "mm":
  4157. boundary = 1.0
  4158. else:
  4159. boundary = 0.0393701
  4160. self.progress.emit(80)
  4161. # Convert everything to strings for use in the xml doc
  4162. svgwidth = str(size[0] + (2 * boundary))
  4163. svgheight = str(size[1] + (2 * boundary))
  4164. minx = str(bounds[0] - boundary)
  4165. miny = str(bounds[1] + boundary + size[1])
  4166. self.log.debug(minx)
  4167. self.log.debug(miny)
  4168. # Add a SVG Header and footer to the svg output from shapely
  4169. # The transform flips the Y Axis so that everything renders
  4170. # properly within svg apps such as inkscape
  4171. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4172. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4173. svg_header += 'width="' + svgwidth + uom + '" '
  4174. svg_header += 'height="' + svgheight + uom + '" '
  4175. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  4176. svg_header += '>'
  4177. svg_header += '<g transform="scale(1,-1)">'
  4178. svg_footer = '</g> </svg>'
  4179. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  4180. self.progress.emit(90)
  4181. # Parse the xml through a xml parser just to add line feeds
  4182. # and to make it look more pretty for the output
  4183. doc = parse_xml_string(svg_elem)
  4184. with open(filename, 'w') as fp:
  4185. fp.write(doc.toprettyxml())
  4186. self.progress.emit(100)
  4187. self.file_saved.emit("SVG", filename)
  4188. self.inform.emit("[success] SVG file exported to " + filename)
  4189. if use_thread is True:
  4190. proc = self.proc_container.new("Generating Film ... Please wait.")
  4191. def job_thread_film(app_obj):
  4192. try:
  4193. make_black_film()
  4194. except Exception as e:
  4195. proc.done()
  4196. return
  4197. proc.done()
  4198. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  4199. else:
  4200. make_black_film()
  4201. def export_excellon(self, obj_name, filename, altium_format=None, use_thread=True):
  4202. """
  4203. Exports a Geometry Object to an Excellon file.
  4204. :param filename: Path to the Excellon file to save to.
  4205. :return:
  4206. """
  4207. if filename is None:
  4208. filename = self.defaults["global_last_save_folder"]
  4209. self.log.debug("export_excellon()")
  4210. format_exc = ';FILE_FORMAT=2:4\n'
  4211. units = ''
  4212. try:
  4213. obj = self.collection.get_by_name(str(obj_name))
  4214. except:
  4215. # TODO: The return behavior has not been established... should raise exception?
  4216. return "Could not retrieve object: %s" % obj_name
  4217. # updated units
  4218. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4219. if units == 'IN' or units == 'INCH':
  4220. units = 'INCH'
  4221. elif units == 'MM' or units == 'METRIC':
  4222. units ='METRIC'
  4223. def make_excellon():
  4224. try:
  4225. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  4226. header = 'M48\n'
  4227. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  4228. (str(self.app.version), str(self.app.version_date))
  4229. header += ';Filename: %s' % str(obj_name) + '\n'
  4230. header += ';Created on : %s' % time_str + '\n'
  4231. if altium_format == None:
  4232. has_slots, excellon_code = obj.export_excellon()
  4233. header += units + '\n'
  4234. for tool in obj.tools:
  4235. if units == 'METRIC':
  4236. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.2f' % float(obj.tools[tool]['C']) + '\n'
  4237. else:
  4238. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.4f' % float(obj.tools[tool]['C']) + '\n'
  4239. else:
  4240. has_slots, excellon_code = obj.export_excellon_altium()
  4241. header += 'INCH,LZ\n'
  4242. header += format_exc
  4243. for tool in obj.tools:
  4244. if units == 'METRIC':
  4245. header += 'T' + str(tool) + 'F00S00' + 'C' + \
  4246. '%.4f' % (float(obj.tools[tool]['C']) / 25.4) + '\n'
  4247. else:
  4248. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.4f' % float(obj.tools[tool]['C']) + '\n'
  4249. header += '%\n'
  4250. footer = 'M30\n'
  4251. exported_excellon = header
  4252. exported_excellon += excellon_code
  4253. exported_excellon += footer
  4254. with open(filename, 'w') as fp:
  4255. fp.write(exported_excellon)
  4256. self.file_saved.emit("Excellon", filename)
  4257. self.inform.emit("[success] Excellon file exported to " + filename)
  4258. except:
  4259. return 'fail'
  4260. if use_thread is True:
  4261. with self.proc_container.new("Exporting Excellon") as proc:
  4262. def job_thread_exc(app_obj):
  4263. ret = make_excellon()
  4264. if ret == 'fail':
  4265. self.inform.emit('[error_notcl] Could not export Excellon file.')
  4266. return
  4267. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  4268. else:
  4269. ret = make_excellon()
  4270. if ret == 'fail':
  4271. self.inform.emit('[error_notcl] Could not export Excellon file.')
  4272. return
  4273. def export_dxf(self, obj_name, filename, use_thread=True):
  4274. """
  4275. Exports a Geometry Object to an DXF file.
  4276. :param filename: Path to the DXF file to save to.
  4277. :return:
  4278. """
  4279. if filename is None:
  4280. filename = self.defaults["global_last_save_folder"]
  4281. self.log.debug("export_dxf()")
  4282. format_exc = ''
  4283. units = ''
  4284. try:
  4285. obj = self.collection.get_by_name(str(obj_name))
  4286. except:
  4287. # TODO: The return behavior has not been established... should raise exception?
  4288. return "Could not retrieve object: %s" % obj_name
  4289. # updated units
  4290. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4291. if units == 'IN' or units == 'INCH':
  4292. units = 'INCH'
  4293. elif units == 'MM' or units == 'METIRC':
  4294. units ='METRIC'
  4295. def make_dxf():
  4296. try:
  4297. dxf_code = obj.export_dxf()
  4298. dxf_code.saveas(filename)
  4299. self.file_saved.emit("DXF", filename)
  4300. self.inform.emit("[success] DXF file exported to " + filename)
  4301. except:
  4302. return 'fail'
  4303. if use_thread is True:
  4304. with self.proc_container.new("Exporting DXF") as proc:
  4305. def job_thread_exc(app_obj):
  4306. ret = make_dxf()
  4307. if ret == 'fail':
  4308. self.inform.emit('[[warning_notcl]] Could not export DXF file.')
  4309. return
  4310. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  4311. else:
  4312. ret = make_dxf()
  4313. if ret == 'fail':
  4314. self.inform.emit('[[warning_notcl]] Could not export DXF file.')
  4315. return
  4316. def import_svg(self, filename, geo_type='geometry', outname=None):
  4317. """
  4318. Adds a new Geometry Object to the projects and populates
  4319. it with shapes extracted from the SVG file.
  4320. :param filename: Path to the SVG file.
  4321. :param outname:
  4322. :return:
  4323. """
  4324. obj_type = ""
  4325. if geo_type is None or geo_type == "geometry":
  4326. obj_type = "geometry"
  4327. elif geo_type == "gerber":
  4328. obj_type = geo_type
  4329. else:
  4330. self.inform.emit("[error_notcl] Not supported type was choosed as parameter. "
  4331. "Only Geometry and Gerber are supported")
  4332. return
  4333. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4334. def obj_init(geo_obj, app_obj):
  4335. geo_obj.import_svg(filename, obj_type, units=units)
  4336. geo_obj.multigeo = False
  4337. with self.proc_container.new("Importing SVG") as proc:
  4338. # Object name
  4339. name = outname or filename.split('/')[-1].split('\\')[-1]
  4340. self.new_object(obj_type, name, obj_init, autoselected=False)
  4341. self.progress.emit(20)
  4342. # Register recent file
  4343. self.file_opened.emit("svg", filename)
  4344. # GUI feedback
  4345. self.inform.emit("[success] Opened: " + filename)
  4346. self.progress.emit(100)
  4347. def import_dxf(self, filename, geo_type='geometry', outname=None):
  4348. """
  4349. Adds a new Geometry Object to the projects and populates
  4350. it with shapes extracted from the DXF file.
  4351. :param filename: Path to the DXF file.
  4352. :param outname:
  4353. :type putname: str
  4354. :return:
  4355. """
  4356. obj_type = ""
  4357. if geo_type is None or geo_type == "geometry":
  4358. obj_type = "geometry"
  4359. elif geo_type == "gerber":
  4360. obj_type = geo_type
  4361. else:
  4362. self.inform.emit("[error_notcl] Not supported type was choosed as parameter. "
  4363. "Only Geometry and Gerber are supported")
  4364. return
  4365. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4366. def obj_init(geo_obj, app_obj):
  4367. geo_obj.import_dxf(filename, obj_type, units=units)
  4368. geo_obj.multigeo = False
  4369. with self.proc_container.new("Importing DXF") as proc:
  4370. # Object name
  4371. name = outname or filename.split('/')[-1].split('\\')[-1]
  4372. self.new_object(obj_type, name, obj_init, autoselected=False)
  4373. self.progress.emit(20)
  4374. # Register recent file
  4375. self.file_opened.emit("dxf", filename)
  4376. # GUI feedback
  4377. self.inform.emit("[success] Opened: " + filename)
  4378. self.progress.emit(100)
  4379. def import_image(self, filename, type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  4380. """
  4381. Adds a new Geometry Object to the projects and populates
  4382. it with shapes extracted from the SVG file.
  4383. :param filename: Path to the SVG file.
  4384. :param outname:
  4385. :return:
  4386. """
  4387. obj_type = ""
  4388. if type is None or type == "geometry":
  4389. obj_type = "geometry"
  4390. elif type == "gerber":
  4391. obj_type = type
  4392. else:
  4393. self.inform.emit("[error_notcl] Not supported type was picked as parameter. "
  4394. "Only Geometry and Gerber are supported")
  4395. return
  4396. def obj_init(geo_obj, app_obj):
  4397. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  4398. geo_obj.multigeo = False
  4399. with self.proc_container.new("Importing Image") as proc:
  4400. # Object name
  4401. name = outname or filename.split('/')[-1].split('\\')[-1]
  4402. units = self.general_options_form.general_app_group.units_radio.get_value()
  4403. self.new_object(obj_type, name, obj_init)
  4404. self.progress.emit(20)
  4405. # Register recent file
  4406. self.file_opened.emit("image", filename)
  4407. # GUI feedback
  4408. self.inform.emit("[success] Opened: " + filename)
  4409. self.progress.emit(100)
  4410. def open_gerber(self, filename, follow=False, outname=None):
  4411. """
  4412. Opens a Gerber file, parses it and creates a new object for
  4413. it in the program. Thread-safe.
  4414. :param outname: Name of the resulting object. None causes the
  4415. name to be that of the file.
  4416. :param filename: Gerber file filename
  4417. :type filename: str
  4418. :param follow: If true, the parser will not create polygons, just lines
  4419. following the gerber path.
  4420. :type follow: bool
  4421. :return: None
  4422. """
  4423. # How the object should be initialized
  4424. def obj_init(gerber_obj, app_obj):
  4425. assert isinstance(gerber_obj, FlatCAMGerber), \
  4426. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  4427. # Opening the file happens here
  4428. self.progress.emit(30)
  4429. try:
  4430. gerber_obj.parse_file(filename, follow=follow)
  4431. except IOError:
  4432. app_obj.inform.emit("[error_notcl] Failed to open file: " + filename)
  4433. app_obj.progress.emit(0)
  4434. self.inform.emit('[error_notcl] Failed to open file: ' + filename)
  4435. return "fail"
  4436. except ParseError as err:
  4437. app_obj.inform.emit("[error_notcl] Failed to parse file: " + filename + ". " + str(err))
  4438. app_obj.progress.emit(0)
  4439. self.log.error(str(err))
  4440. return "fail"
  4441. except:
  4442. msg = "[error] An internal error has ocurred. See shell.\n"
  4443. msg += traceback.format_exc()
  4444. app_obj.inform.emit(msg)
  4445. return "fail"
  4446. if gerber_obj.is_empty():
  4447. # app_obj.inform.emit("[error] No geometry found in file: " + filename)
  4448. # self.collection.set_active(gerber_obj.options["name"])
  4449. # self.collection.delete_active()
  4450. self.inform.emit("[error_notcl] Object is not Gerber file or empty. Aborting object creation.")
  4451. return "fail"
  4452. # Further parsing
  4453. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  4454. if follow is False:
  4455. App.log.debug("open_gerber()")
  4456. else:
  4457. App.log.debug("open_gerber() with 'follow' attribute")
  4458. with self.proc_container.new("Opening Gerber") as proc:
  4459. self.progress.emit(10)
  4460. # Object name
  4461. name = outname or filename.split('/')[-1].split('\\')[-1]
  4462. ### Object creation ###
  4463. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  4464. if ret == 'fail':
  4465. self.inform.emit('[error_notcl] Open Gerber failed. Probable not a Gerber file.')
  4466. return
  4467. # Register recent file
  4468. self.file_opened.emit("gerber", filename)
  4469. self.progress.emit(100)
  4470. # GUI feedback
  4471. self.inform.emit("[success] Opened: " + filename)
  4472. def open_excellon(self, filename, outname=None):
  4473. """
  4474. Opens an Excellon file, parses it and creates a new object for
  4475. it in the program. Thread-safe.
  4476. :param outname: Name of the resulting object. None causes the
  4477. name to be that of the file.
  4478. :param filename: Excellon file filename
  4479. :type filename: str
  4480. :return: None
  4481. """
  4482. App.log.debug("open_excellon()")
  4483. #self.progress.emit(10)
  4484. # How the object should be initialized
  4485. def obj_init(excellon_obj, app_obj):
  4486. # self.progress.emit(20)
  4487. try:
  4488. ret = excellon_obj.parse_file(filename)
  4489. if ret == "fail":
  4490. log.debug("Excellon parsing failed.")
  4491. self.inform.emit("[error_notcl] This is not Excellon file.")
  4492. return "fail"
  4493. except IOError:
  4494. app_obj.inform.emit("[error_notcl] Cannot open file: " + filename)
  4495. log.debug("Could not open Excellon object.")
  4496. self.progress.emit(0) # TODO: self and app_bjj mixed
  4497. return "fail"
  4498. except:
  4499. msg = "[error_notcl] An internal error has occurred. See shell.\n"
  4500. msg += traceback.format_exc()
  4501. app_obj.inform.emit(msg)
  4502. return "fail"
  4503. ret = excellon_obj.create_geometry()
  4504. if ret == 'fail':
  4505. log.debug("Could not create geometry for Excellon object.")
  4506. return "fail"
  4507. if excellon_obj.is_empty():
  4508. app_obj.inform.emit("[error_notcl] No geometry found in file: " + filename)
  4509. return "fail"
  4510. with self.proc_container.new("Opening Excellon."):
  4511. # Object name
  4512. name = outname or filename.split('/')[-1].split('\\')[-1]
  4513. ret = self.new_object("excellon", name, obj_init, autoselected=False)
  4514. if ret == 'fail':
  4515. self.inform.emit('[error_notcl] Open Excellon file failed. Probable not an Excellon file.')
  4516. return
  4517. # Register recent file
  4518. self.file_opened.emit("excellon", filename)
  4519. # GUI feedback
  4520. self.inform.emit("[success] Opened: " + filename)
  4521. # self.progress.emit(100)
  4522. def open_gcode(self, filename, outname=None):
  4523. """
  4524. Opens a G-gcode file, parses it and creates a new object for
  4525. it in the program. Thread-safe.
  4526. :param outname: Name of the resulting object. None causes the
  4527. name to be that of the file.
  4528. :param filename: G-code file filename
  4529. :type filename: str
  4530. :return: None
  4531. """
  4532. App.log.debug("open_gcode()")
  4533. # How the object should be initialized
  4534. def obj_init(job_obj, app_obj_):
  4535. """
  4536. :type app_obj_: App
  4537. """
  4538. assert isinstance(app_obj_, App), \
  4539. "Initializer expected App, got %s" % type(app_obj_)
  4540. self.progress.emit(10)
  4541. try:
  4542. f = open(filename)
  4543. gcode = f.read()
  4544. f.close()
  4545. except IOError:
  4546. app_obj_.inform.emit("[error_notcl] Failed to open " + filename)
  4547. self.progress.emit(0)
  4548. return "fail"
  4549. job_obj.gcode = gcode
  4550. self.progress.emit(20)
  4551. ret = job_obj.gcode_parse()
  4552. if ret == "fail":
  4553. self.inform.emit("[error_notcl] This is not GCODE")
  4554. return "fail"
  4555. self.progress.emit(60)
  4556. job_obj.create_geometry()
  4557. with self.proc_container.new("Opening G-Code."):
  4558. # Object name
  4559. name = outname or filename.split('/')[-1].split('\\')[-1]
  4560. # New object creation and file processing
  4561. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  4562. if ret == 'fail':
  4563. self.inform.emit("[error_notcl] Failed to create CNCJob Object. Probable not a GCode file.\n "
  4564. "Attempting to create a FlatCAM CNCJob Object from "
  4565. "G-Code file failed during processing")
  4566. return "fail"
  4567. # Register recent file
  4568. self.file_opened.emit("cncjob", filename)
  4569. # GUI feedback
  4570. self.inform.emit("[success] Opened: " + filename)
  4571. self.progress.emit(100)
  4572. def open_project(self, filename, run_from_arg=None):
  4573. """
  4574. Loads a project from the specified file.
  4575. 1) Loads and parses file
  4576. 2) Registers the file as recently opened.
  4577. 3) Calls on_file_new()
  4578. 4) Updates options
  4579. 5) Calls new_object() with the object's from_dict() as init method.
  4580. 6) Calls plot_all()
  4581. :param filename: Name of the file from which to load.
  4582. :type filename: str
  4583. :return: None
  4584. """
  4585. App.log.debug("Opening project: " + filename)
  4586. # Open and parse
  4587. try:
  4588. f = open(filename, 'r')
  4589. except IOError:
  4590. App.log.error("Failed to open project file: %s" % filename)
  4591. self.inform.emit("[error_notcl] Failed to open project file: %s" % filename)
  4592. return
  4593. try:
  4594. d = json.load(f, object_hook=dict2obj)
  4595. except:
  4596. App.log.error("Failed to parse project file: %s" % filename)
  4597. self.inform.emit("[error_notcl] Failed to parse project file: %s" % filename)
  4598. f.close()
  4599. return
  4600. self.file_opened.emit("project", filename)
  4601. # Clear the current project
  4602. ## NOT THREAD SAFE ##
  4603. if run_from_arg is True:
  4604. pass
  4605. else:
  4606. self.on_file_new()
  4607. #Project options
  4608. self.options.update(d['options'])
  4609. self.project_filename = filename
  4610. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4611. self.set_screen_units(self.options["units"])
  4612. # Re create objects
  4613. App.log.debug("Re-creating objects...")
  4614. for obj in d['objs']:
  4615. def obj_init(obj_inst, app_inst):
  4616. obj_inst.from_dict(obj)
  4617. App.log.debug(obj['kind'] + ": " + obj['options']['name'])
  4618. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  4619. # self.plot_all()
  4620. self.inform.emit("[success] Project loaded from: " + filename)
  4621. App.log.debug("Project loaded")
  4622. def propagate_defaults(self, silent=False):
  4623. """
  4624. This method is used to set default values in classes. It's
  4625. an alternative to project options but allows the use
  4626. of values invisible to the user.
  4627. :return: None
  4628. """
  4629. if silent is False:
  4630. self.log.debug("propagate_defaults()")
  4631. # Which objects to update the given parameters.
  4632. routes = {
  4633. "global_zdownrate": CNCjob,
  4634. "excellon_zeros": Excellon,
  4635. "excellon_format_upper_in": Excellon,
  4636. "excellon_format_lower_in": Excellon,
  4637. "excellon_format_upper_mm": Excellon,
  4638. "excellon_format_lower_mm": Excellon,
  4639. "excellon_units": Excellon,
  4640. "gerber_use_buffer_for_union": Gerber,
  4641. "geometry_multidepth": Geometry
  4642. }
  4643. for param in routes:
  4644. if param in routes[param].defaults:
  4645. try:
  4646. routes[param].defaults[param] = self.defaults[param]
  4647. if silent is False:
  4648. self.log.debug(" " + param + " OK")
  4649. except KeyError:
  4650. if silent is False:
  4651. self.log.debug(" ERROR: " + param + " not in defaults.")
  4652. else:
  4653. # Try extracting the name:
  4654. # classname_param here is param in the object
  4655. if param.find(routes[param].__name__.lower() + "_") == 0:
  4656. p = param[len(routes[param].__name__) + 1:]
  4657. if p in routes[param].defaults:
  4658. routes[param].defaults[p] = self.defaults[param]
  4659. if silent is False:
  4660. self.log.debug(" " + param + " OK!")
  4661. def restore_main_win_geom(self):
  4662. try:
  4663. self.ui.setGeometry(self.defaults["global_def_win_x"],
  4664. self.defaults["global_def_win_y"],
  4665. self.defaults["global_def_win_w"],
  4666. self.defaults["global_def_win_h"])
  4667. self.ui.splitter.setSizes([self.defaults["def_notebook_width"], 0])
  4668. except KeyError:
  4669. pass
  4670. def plot_all(self):
  4671. """
  4672. Re-generates all plots from all objects.
  4673. :return: None
  4674. """
  4675. self.log.debug("Plot_all()")
  4676. for obj in self.collection.get_list():
  4677. def worker_task(obj):
  4678. with self.proc_container.new("Plotting"):
  4679. obj.plot()
  4680. self.object_plotted.emit(obj)
  4681. # Send to worker
  4682. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  4683. # self.progress.emit(10)
  4684. #
  4685. # def worker_task(app_obj):
  4686. # print "worker task"
  4687. # percentage = 0.1
  4688. # try:
  4689. # delta = 0.9 / len(self.collection.get_list())
  4690. # except ZeroDivisionError:
  4691. # self.progress.emit(0)
  4692. # return
  4693. # for obj in self.collection.get_list():
  4694. # with self.proc_container.new("Plotting"):
  4695. # obj.plot()
  4696. # app_obj.object_plotted.emit(obj)
  4697. #
  4698. # percentage += delta
  4699. # self.progress.emit(int(percentage*100))
  4700. #
  4701. # self.progress.emit(0)
  4702. # self.plots_updated.emit()
  4703. #
  4704. # # Send to worker
  4705. # #self.worker.add_task(worker_task, [self])
  4706. # self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  4707. def register_folder(self, filename):
  4708. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  4709. def register_save_folder(self, filename):
  4710. self.defaults['global_last_save_folder'] = os.path.split(str(filename))[0]
  4711. def set_progress_bar(self, percentage, text=""):
  4712. self.ui.progress_bar.setValue(int(percentage))
  4713. def setup_shell(self):
  4714. """
  4715. Creates shell functions. Runs once at startup.
  4716. :return: None
  4717. """
  4718. self.log.debug("setup_shell()")
  4719. def shelp(p=None):
  4720. if not p:
  4721. return "Available commands:\n" + \
  4722. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  4723. "\n\nType help <command_name> for usage.\n Example: help open_gerber"
  4724. if p not in commands:
  4725. return "Unknown command: %s" % p
  4726. return commands[p]["help"]
  4727. # --- Migrated to new architecture ---
  4728. # def options(name):
  4729. # ops = self.collection.get_by_name(str(name)).options
  4730. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  4731. def h(*args):
  4732. """
  4733. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  4734. and standalone parameters into list.
  4735. """
  4736. kwa = {}
  4737. a = []
  4738. n = len(args)
  4739. name = None
  4740. for i in range(n):
  4741. match = re.search(r'^-([a-zA-Z].*)', args[i])
  4742. if match:
  4743. assert name is None
  4744. name = match.group(1)
  4745. continue
  4746. if name is None:
  4747. a.append(args[i])
  4748. else:
  4749. kwa[name] = args[i]
  4750. name = None
  4751. return a, kwa
  4752. @contextmanager
  4753. def wait_signal(signal, timeout=10000):
  4754. """
  4755. Block loop until signal emitted, timeout (ms) elapses
  4756. or unhandled exception happens in a thread.
  4757. :param signal: Signal to wait for.
  4758. """
  4759. loop = QtCore.QEventLoop()
  4760. # Normal termination
  4761. signal.connect(loop.quit)
  4762. # Termination by exception in thread
  4763. self.thread_exception.connect(loop.quit)
  4764. status = {'timed_out': False}
  4765. def report_quit():
  4766. status['timed_out'] = True
  4767. loop.quit()
  4768. yield
  4769. # Temporarily change how exceptions are managed.
  4770. oeh = sys.excepthook
  4771. ex = []
  4772. def except_hook(type_, value, traceback_):
  4773. ex.append(value)
  4774. oeh(type_, value, traceback_)
  4775. sys.excepthook = except_hook
  4776. # Terminate on timeout
  4777. if timeout is not None:
  4778. QtCore.QTimer.singleShot(timeout, report_quit)
  4779. #### Block ####
  4780. loop.exec_()
  4781. # Restore exception management
  4782. sys.excepthook = oeh
  4783. if ex:
  4784. self.raiseTclError(str(ex[0]))
  4785. if status['timed_out']:
  4786. raise Exception('Timed out!')
  4787. def make_docs():
  4788. output = ''
  4789. import collections
  4790. od = collections.OrderedDict(sorted(commands.items()))
  4791. for cmd_, val in od.items():
  4792. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  4793. t = val['help']
  4794. usage_i = t.find('>')
  4795. if usage_i < 0:
  4796. expl = t
  4797. output += expl + '\n\n'
  4798. continue
  4799. expl = t[:usage_i - 1]
  4800. output += expl + '\n\n'
  4801. end_usage_i = t[usage_i:].find('\n')
  4802. if end_usage_i < 0:
  4803. end_usage_i = len(t[usage_i:])
  4804. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  4805. else:
  4806. extras = t[usage_i+end_usage_i+1:]
  4807. parts = [s.strip() for s in extras.split('\n')]
  4808. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  4809. for p in parts:
  4810. output += ' ' + p + '\n\n'
  4811. return output
  4812. '''
  4813. Howto implement TCL shell commands:
  4814. All parameters passed to command should be possible to set as None and test it afterwards.
  4815. This is because we need to see error caused in tcl,
  4816. if None value as default parameter is not allowed TCL will return empty error.
  4817. Use:
  4818. def mycommand(name=None,...):
  4819. Test it like this:
  4820. if name is None:
  4821. self.raise_tcl_error('Argument name is missing.')
  4822. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  4823. otherwise we will miss it and processing will silently continue.
  4824. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  4825. which is catched in exec_command and displayed in TCL shell console with red background.
  4826. Error in console is displayed with TCL trace.
  4827. This behavior works only within main thread,
  4828. errors with promissed tasks can be catched and detected only with log.
  4829. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for TCL shell.
  4830. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  4831. '''
  4832. commands = {
  4833. 'help': {
  4834. 'fcn': shelp,
  4835. 'help': "Shows list of commands."
  4836. },
  4837. }
  4838. # Import/overwrite tcl commands as objects of TclCommand descendants
  4839. # This modifies the variable 'commands'.
  4840. tclCommands.register_all_commands(self, commands)
  4841. # Add commands to the tcl interpreter
  4842. for cmd in commands:
  4843. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  4844. # Make the tcl puts function return instead of print to stdout
  4845. self.tcl.eval('''
  4846. rename puts original_puts
  4847. proc puts {args} {
  4848. if {[llength $args] == 1} {
  4849. return "[lindex $args 0]"
  4850. } else {
  4851. eval original_puts $args
  4852. }
  4853. }
  4854. ''')
  4855. def setup_recent_items(self):
  4856. # TODO: Move this to constructor
  4857. icons = {
  4858. "gerber": "share/flatcam_icon16.png",
  4859. "excellon": "share/drill16.png",
  4860. "cncjob": "share/cnc16.png",
  4861. "project": "share/project16.png",
  4862. "svg": "share/geometry16.png",
  4863. "dxf": "share/dxf16.png",
  4864. "image": "share/image16.png"
  4865. }
  4866. openers = {
  4867. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  4868. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  4869. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  4870. 'project': self.open_project,
  4871. 'svg': self.import_svg,
  4872. 'dxf': self.import_dxf,
  4873. 'image': self.import_image
  4874. }
  4875. # Open file
  4876. try:
  4877. f = open(self.data_path + '/recent.json')
  4878. except IOError:
  4879. App.log.error("Failed to load recent item list.")
  4880. self.inform.emit("[error_notcl] Failed to load recent item list.")
  4881. return
  4882. try:
  4883. self.recent = json.load(f)
  4884. except json.scanner.JSONDecodeError:
  4885. App.log.error("Failed to parse recent item list.")
  4886. self.inform.emit("[error_notcl] Failed to parse recent item list.")
  4887. f.close()
  4888. return
  4889. f.close()
  4890. # Closure needed to create callbacks in a loop.
  4891. # Otherwise late binding occurs.
  4892. def make_callback(func, fname):
  4893. def opener():
  4894. func(fname)
  4895. return opener
  4896. def reset_recent():
  4897. # Reset menu
  4898. self.ui.recent.clear()
  4899. self.recent = []
  4900. try:
  4901. f = open(self.data_path + '/recent.json', 'w')
  4902. except IOError:
  4903. App.log.error("Failed to open recent items file for writing.")
  4904. return
  4905. json.dump(self.recent, f)
  4906. # Reset menu
  4907. self.ui.recent.clear()
  4908. # Create menu items
  4909. for recent in self.recent:
  4910. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  4911. try:
  4912. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  4913. # Attach callback
  4914. o = make_callback(openers[recent["kind"]], recent['filename'])
  4915. action.triggered.connect(o)
  4916. self.ui.recent.addAction(action)
  4917. except KeyError:
  4918. App.log.error("Unsupported file type: %s" % recent["kind"])
  4919. # Last action in Recent Files menu is one that Clear the content
  4920. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), "Clear Recent files", self)
  4921. clear_action.triggered.connect(reset_recent)
  4922. self.ui.recent.addSeparator()
  4923. self.ui.recent.addAction(clear_action)
  4924. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  4925. # self.ui.menufilerecent.set_submenu(recent_menu)
  4926. # recent_menu.show_all()
  4927. # self.ui.recent.show()
  4928. self.log.debug("Recent items list has been populated.")
  4929. def setup_component_editor(self):
  4930. label = QtWidgets.QLabel("Choose an item from Project")
  4931. label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  4932. self.ui.selected_scroll_area.setWidget(label)
  4933. def setup_obj_classes(self):
  4934. """
  4935. Sets up application specifics on the FlatCAMObj class.
  4936. :return: None
  4937. """
  4938. FlatCAMObj.app = self
  4939. ObjectCollection.app = self
  4940. FCProcess.app = self
  4941. FCProcessContainer.app = self
  4942. def version_check(self):
  4943. """
  4944. Checks for the latest version of the program. Alerts the
  4945. user if theirs is outdated. This method is meant to be run
  4946. in a separate thread.
  4947. :return: None
  4948. """
  4949. self.log.debug("version_check()")
  4950. if self.general_defaults_form.general_gui_group.send_stats_cb.get_value() is True:
  4951. full_url = App.version_url + \
  4952. "?s=" + str(self.defaults['global_serial']) + \
  4953. "&v=" + str(self.version) + \
  4954. "&os=" + str(self.os) + \
  4955. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  4956. else:
  4957. # no_stats dict; just so it won't break things on website
  4958. no_ststs_dict = {}
  4959. no_ststs_dict["global_ststs"] = {}
  4960. full_url = App.version_url + \
  4961. "?s=" + str(self.defaults['global_serial']) + \
  4962. "&v=" + str(self.version) + \
  4963. "&os=" + str(self.os) + \
  4964. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  4965. App.log.debug("Checking for updates @ %s" % full_url)
  4966. ### Get the data
  4967. try:
  4968. f = urllib.request.urlopen(full_url)
  4969. except:
  4970. # App.log.warning("Failed checking for latest version. Could not connect.")
  4971. self.log.warning("Failed checking for latest version. Could not connect.")
  4972. self.inform.emit("[warning_notcl] Failed checking for latest version. Could not connect.")
  4973. return
  4974. try:
  4975. data = json.load(f)
  4976. except Exception as e:
  4977. App.log.error("Could not parse information about latest version.")
  4978. self.inform.emit("[error_notcl] Could not parse information about latest version.")
  4979. App.log.debug("json.load(): %s" % str(e))
  4980. f.close()
  4981. return
  4982. f.close()
  4983. ### Latest version?
  4984. if self.version >= data["version"]:
  4985. App.log.debug("FlatCAM is up to date!")
  4986. self.inform.emit("[success] FlatCAM is up to date!")
  4987. return
  4988. App.log.debug("Newer version available.")
  4989. self.message.emit(
  4990. "Newer Version Available",
  4991. str("There is a newer version of FlatCAM " +
  4992. "available for download:<br><br>" +
  4993. "<B>" + data["name"] + "</b><br>" +
  4994. data["message"].replace("\n", "<br>")),
  4995. "info"
  4996. )
  4997. # TODO: FIX THIS
  4998. '''
  4999. By default this is not threaded
  5000. If threaded the app give warnings like this:
  5001. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  5002. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  5003. '''
  5004. def enable_plots(self, objects, threaded=False):
  5005. if threaded is True:
  5006. def worker_task(app_obj):
  5007. percentage = 0.1
  5008. try:
  5009. delta = 0.9 / len(objects)
  5010. except ZeroDivisionError:
  5011. self.progress.emit(0)
  5012. return
  5013. for obj in objects:
  5014. obj.options['plot'] = True
  5015. percentage += delta
  5016. self.progress.emit(int(percentage*100))
  5017. self.progress.emit(0)
  5018. self.plots_updated.emit()
  5019. self.collection.update_view()
  5020. # Send to worker
  5021. # self.worker.add_task(worker_task, [self])
  5022. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5023. else:
  5024. for obj in objects:
  5025. obj.options['plot'] = True
  5026. self.progress.emit(0)
  5027. self.plots_updated.emit()
  5028. self.collection.update_view()
  5029. # TODO: FIX THIS
  5030. '''
  5031. By default this is not threaded
  5032. If threaded the app give warnings like this:
  5033. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  5034. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  5035. '''
  5036. def disable_plots(self, objects, threaded=False):
  5037. # TODO: This method is very similar to replot_all. Try to merge.
  5038. """
  5039. Disables plots
  5040. :param objects: list
  5041. Objects to be disabled
  5042. :return:
  5043. """
  5044. if threaded is True:
  5045. self.progress.emit(10)
  5046. def worker_task(app_obj):
  5047. percentage = 0.1
  5048. try:
  5049. delta = 0.9 / len(objects)
  5050. except ZeroDivisionError:
  5051. self.progress.emit(0)
  5052. return
  5053. for obj in objects:
  5054. obj.options['plot'] = False
  5055. percentage += delta
  5056. self.progress.emit(int(percentage*100))
  5057. self.progress.emit(0)
  5058. self.plots_updated.emit()
  5059. self.collection.update_view()
  5060. # Send to worker
  5061. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5062. else:
  5063. for obj in objects:
  5064. obj.options['plot'] = False
  5065. self.plots_updated.emit()
  5066. self.collection.update_view()
  5067. def clear_plots(self):
  5068. objects = self.collection.get_list()
  5069. for obj in objects:
  5070. obj.clear(obj == objects[-1])
  5071. # Clear pool to free memory
  5072. self.clear_pool()
  5073. def generate_cnc_job(self, objects):
  5074. for obj in objects:
  5075. obj.generatecncjob()
  5076. def save_project(self, filename):
  5077. """
  5078. Saves the current project to the specified file.
  5079. :param filename: Name of the file in which to save.
  5080. :type filename: str
  5081. :return: None
  5082. """
  5083. self.log.debug("save_project()")
  5084. with self.proc_container.new("Saving FlatCAM Project") as proc:
  5085. ## Capture the latest changes
  5086. # Current object
  5087. try:
  5088. self.collection.get_active().read_form()
  5089. except:
  5090. self.log.debug("[warning] There was no active object")
  5091. pass
  5092. # Project options
  5093. self.options_read_form()
  5094. # Serialize the whole project
  5095. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  5096. "options": self.options,
  5097. "version": self.version}
  5098. # Open file
  5099. try:
  5100. f = open(filename, 'w')
  5101. except IOError:
  5102. App.log.error("[error] Failed to open file for saving: %s", filename)
  5103. return
  5104. # Write
  5105. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  5106. f.close()
  5107. # verification of the saved project
  5108. # Open and parse
  5109. try:
  5110. saved_f = open(filename, 'r')
  5111. except IOError:
  5112. self.inform.emit("[error_notcl] Failed to verify project file: %s. Retry to save it." % filename)
  5113. return
  5114. try:
  5115. saved_d = json.load(saved_f, object_hook=dict2obj)
  5116. except:
  5117. self.inform.emit("[error_notcl] Failed to parse saved project file: %s. Retry to save it." % filename)
  5118. f.close()
  5119. return
  5120. saved_f.close()
  5121. if 'version' in saved_d:
  5122. self.inform.emit("[success] Project saved to: %s" % filename)
  5123. else:
  5124. self.inform.emit("[error_notcl] Failed to save project file: %s. Retry to save it." % filename)
  5125. def on_options_app2project(self):
  5126. """
  5127. Callback for Options->Transfer Options->App=>Project. Copies options
  5128. from application defaults to project defaults.
  5129. :return: None
  5130. """
  5131. self.report_usage("on_options_app2project")
  5132. self.defaults_read_form()
  5133. self.options.update(self.defaults)
  5134. self.options_write_form()
  5135. def on_options_project2app(self):
  5136. """
  5137. Callback for Options->Transfer Options->Project=>App. Copies options
  5138. from project defaults to application defaults.
  5139. :return: None
  5140. """
  5141. self.report_usage("on_options_project2app")
  5142. self.options_read_form()
  5143. self.defaults.update(self.options)
  5144. self.defaults_write_form()
  5145. def on_options_project2object(self):
  5146. """
  5147. Callback for Options->Transfer Options->Project=>Object. Copies options
  5148. from project defaults to the currently selected object.
  5149. :return: None
  5150. """
  5151. self.report_usage("on_options_project2object")
  5152. self.options_read_form()
  5153. obj = self.collection.get_active()
  5154. if obj is None:
  5155. self.inform.emit("WARNING: No object selected.")
  5156. return
  5157. for option in self.options:
  5158. if option.find(obj.kind + "_") == 0:
  5159. oname = option[len(obj.kind) + 1:]
  5160. obj.options[oname] = self.options[option]
  5161. obj.to_form() # Update UI
  5162. def on_options_object2project(self):
  5163. """
  5164. Callback for Options->Transfer Options->Object=>Project. Copies options
  5165. from the currently selected object to project defaults.
  5166. :return: None
  5167. """
  5168. self.report_usage("on_options_object2project")
  5169. obj = self.collection.get_active()
  5170. if obj is None:
  5171. self.inform.emit("WARNING: No object selected.")
  5172. return
  5173. obj.read_form()
  5174. for option in obj.options:
  5175. if option in ['name']: # TODO: Handle this better...
  5176. continue
  5177. self.options[obj.kind + "_" + option] = obj.options[option]
  5178. self.options_write_form()
  5179. def on_options_object2app(self):
  5180. """
  5181. Callback for Options->Transfer Options->Object=>App. Copies options
  5182. from the currently selected object to application defaults.
  5183. :return: None
  5184. """
  5185. self.report_usage("on_options_object2app")
  5186. obj = self.collection.get_active()
  5187. if obj is None:
  5188. self.inform.emit("WARNING: No object selected.")
  5189. return
  5190. obj.read_form()
  5191. for option in obj.options:
  5192. if option in ['name']: # TODO: Handle this better...
  5193. continue
  5194. self.defaults[obj.kind + "_" + option] = obj.options[option]
  5195. self.defaults_write_form()
  5196. def on_options_app2object(self):
  5197. """
  5198. Callback for Options->Transfer Options->App=>Object. Copies options
  5199. from application defaults to the currently selected object.
  5200. :return: None
  5201. """
  5202. self.report_usage("on_options_app2object")
  5203. self.defaults_read_form()
  5204. obj = self.collection.get_active()
  5205. if obj is None:
  5206. self.inform.emit("WARNING: No object selected.")
  5207. return
  5208. for option in self.defaults:
  5209. if option.find(obj.kind + "_") == 0:
  5210. oname = option[len(obj.kind) + 1:]
  5211. obj.options[oname] = self.defaults[option]
  5212. obj.to_form() # Update UI
  5213. # end of file