FlatCAMApp.py 328 KB

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