FlatCAMApp.py 560 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431
  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
  9. import urllib.parse
  10. import urllib.error
  11. import webbrowser
  12. import getopt
  13. import random
  14. import simplejson as json
  15. import lzma
  16. import threading
  17. import shutil
  18. from stat import S_IREAD, S_IRGRP, S_IROTH
  19. import subprocess
  20. import ctypes
  21. import tkinter as tk
  22. from PyQt5 import QtPrintSupport
  23. from contextlib import contextmanager
  24. import gc
  25. from xml.dom.minidom import parseString as parse_xml_string
  26. from multiprocessing.connection import Listener, Client
  27. from multiprocessing import Pool, cpu_count
  28. import socket
  29. from array import array
  30. import vispy.scene as scene
  31. # #######################################
  32. # # Imports part of FlatCAM ##
  33. # #######################################
  34. from ObjectCollection import *
  35. from FlatCAMObj import *
  36. from camlib import to_dict, dict2obj, ET, ParseError
  37. from flatcamGUI.PlotCanvas import *
  38. from flatcamGUI.PlotCanvasLegacy import *
  39. from flatcamGUI.FlatCAMGUI import *
  40. from FlatCAMCommon import LoudDict
  41. from FlatCAMPostProc import load_postprocessors
  42. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  43. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  44. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  45. from flatcamEditors.FlatCAMTextEditor import TextEditor
  46. from FlatCAMProcess import *
  47. from FlatCAMWorkerStack import WorkerStack
  48. # from flatcamGUI.VisPyVisuals import Color
  49. from vispy.gloo.util import _screenshot
  50. from vispy.io import write_png
  51. from flatcamTools import *
  52. import tclCommands
  53. import gettext
  54. import FlatCAMTranslation as fcTranslate
  55. import builtins
  56. if sys.platform == 'win32':
  57. import winreg
  58. fcTranslate.apply_language('strings')
  59. if '_' not in builtins.__dict__:
  60. _ = gettext.gettext
  61. class App(QtCore.QObject):
  62. # ########################################
  63. # # App ###
  64. # ########################################
  65. """
  66. The main application class. The constructor starts the GUI.
  67. """
  68. # Get Cmd Line Options
  69. cmd_line_shellfile = ''
  70. cmd_line_shellvar = ''
  71. cmd_line_headless = None
  72. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  73. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  74. "FlatCam.py --headless=1"
  75. try:
  76. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  77. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  78. "shellvar=",
  79. "headless=",
  80. "multiprocessing-fork="])
  81. except getopt.GetoptError:
  82. print(cmd_line_help)
  83. sys.exit(2)
  84. for opt, arg in cmd_line_options:
  85. if opt == '-h':
  86. print(cmd_line_help)
  87. sys.exit()
  88. elif opt == '--shellfile':
  89. cmd_line_shellfile = arg
  90. elif opt == '--shellvar':
  91. cmd_line_shellvar = arg
  92. elif opt == '--headless':
  93. try:
  94. cmd_line_headless = eval(arg)
  95. except NameError:
  96. pass
  97. # ## Logging ###
  98. log = logging.getLogger('base')
  99. log.setLevel(logging.DEBUG)
  100. # log.setLevel(logging.WARNING)
  101. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  102. handler = logging.StreamHandler()
  103. handler.setFormatter(formatter)
  104. log.addHandler(handler)
  105. # ##########################################################################
  106. # ################## Version and VERSION DATE ##############################
  107. # ##########################################################################
  108. version = 8.99
  109. version_date = "2019/10/30"
  110. beta = True
  111. engine = '3D'
  112. # current date now
  113. date = str(datetime.today()).rpartition('.')[0]
  114. date = ''.join(c for c in date if c not in ':-')
  115. date = date.replace(' ', '_')
  116. # URL for update checks and statistics
  117. version_url = "http://flatcam.org/version"
  118. # App URL
  119. app_url = "http://flatcam.org"
  120. # Manual URL
  121. manual_url = "http://flatcam.org/manual/index.html"
  122. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  123. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  124. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  125. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  126. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  127. # this variable will hold the project status
  128. # if True it will mean that the project was modified and not saved
  129. should_we_save = False
  130. # flag is True if saving action has been triggered
  131. save_in_progress = False
  132. # ###########################################################################
  133. # ############################# Signals ################################
  134. # ###########################################################################
  135. # Inform the user
  136. # Handled by:
  137. # * App.info() --> Print on the status bar
  138. inform = QtCore.pyqtSignal(str)
  139. app_quit = QtCore.pyqtSignal()
  140. # General purpose background task
  141. worker_task = QtCore.pyqtSignal(dict)
  142. # File opened
  143. # Handled by:
  144. # * register_folder()
  145. # * register_recent()
  146. # Note: Setting the parameters to unicode does not seem
  147. # to have an effect. Then are received as Qstring
  148. # anyway.
  149. # File type and filename
  150. file_opened = QtCore.pyqtSignal(str, str)
  151. # File type and filename
  152. file_saved = QtCore.pyqtSignal(str, str)
  153. # Percentage of progress
  154. progress = QtCore.pyqtSignal(int)
  155. plots_updated = QtCore.pyqtSignal()
  156. # Emitted by new_object() and passes the new object as argument, plot flag.
  157. # on_object_created() adds the object to the collection, plots on appropriate flag
  158. # and emits new_object_available.
  159. object_created = QtCore.pyqtSignal(object, bool, bool)
  160. # Emitted when a object has been changed (like scaled, mirrored)
  161. object_changed = QtCore.pyqtSignal(object)
  162. # Emitted after object has been plotted.
  163. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  164. object_plotted = QtCore.pyqtSignal(object)
  165. # Emitted when a new object has been added or deleted from/to the collection
  166. object_status_changed = QtCore.pyqtSignal(object, str, str)
  167. message = QtCore.pyqtSignal(str, str, str)
  168. # Emmited when shell command is finished(one command only)
  169. shell_command_finished = QtCore.pyqtSignal(object)
  170. # Emitted when multiprocess pool has been recreated
  171. pool_recreated = QtCore.pyqtSignal(object)
  172. # Emitted when an unhandled exception happens
  173. # in the worker task.
  174. thread_exception = QtCore.pyqtSignal(object)
  175. # used to signal that there are arguments for the app
  176. args_at_startup = QtCore.pyqtSignal(list)
  177. # a reusable signal to replot a list of objects
  178. # should be disconnected after use so it can be reused
  179. replot_signal = pyqtSignal(list)
  180. def __init__(self, user_defaults=True, post_gui=None):
  181. """
  182. Starts the application.
  183. :return: app
  184. :rtype: App
  185. """
  186. App.log.info("FlatCAM Starting...")
  187. self.main_thread = QtWidgets.QApplication.instance().thread()
  188. # ############################################################################
  189. # # ################# OS-specific ############################################
  190. # ############################################################################
  191. portable = False
  192. # Folder for user settings.
  193. if sys.platform == 'win32':
  194. # #########################################################################
  195. # Setup the listening thread for another instance launching with args #####
  196. # #########################################################################
  197. # make sure the thread is stored by using a self. otherwise it's garbage collected
  198. self.th = QtCore.QThread()
  199. self.th.start(priority=QtCore.QThread.LowestPriority)
  200. self.new_launch = ArgsThread()
  201. self.new_launch.open_signal[list].connect(self.on_startup_args)
  202. self.new_launch.moveToThread(self.th)
  203. self.new_launch.start.emit()
  204. from win32com.shell import shell, shellcon
  205. if platform.architecture()[0] == '32bit':
  206. App.log.debug("Win32!")
  207. else:
  208. App.log.debug("Win64!")
  209. # #########################################################################
  210. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  211. # #########################################################################
  212. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  213. try:
  214. with open(config_file, 'r'):
  215. pass
  216. except FileNotFoundError:
  217. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  218. try:
  219. with open(config_file, 'r') as f:
  220. try:
  221. for line in f:
  222. param = str(line).replace('\n', '').rpartition('=')
  223. if param[0] == 'portable':
  224. try:
  225. portable = eval(param[2])
  226. except NameError:
  227. portable = False
  228. if param[0] == 'headless':
  229. if param[2].lower() == 'true':
  230. self.cmd_line_headless = 1
  231. else:
  232. self.cmd_line_headless = None
  233. except Exception as e:
  234. log.debug('App.__init__() -->%s' % str(e))
  235. return
  236. except FileNotFoundError as e:
  237. log.debug(str(e))
  238. pass
  239. if portable is False:
  240. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  241. else:
  242. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  243. self.os = 'windows'
  244. else: # Linux/Unix/MacOS
  245. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  246. self.os = 'unix'
  247. # ##########################################################################
  248. # ################## Setup folders and files ###############################
  249. # ##########################################################################
  250. if not os.path.exists(self.data_path):
  251. os.makedirs(self.data_path)
  252. App.log.debug('Created data folder: ' + self.data_path)
  253. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  254. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  255. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  256. if not os.path.exists(self.postprocessorpaths):
  257. os.makedirs(self.postprocessorpaths)
  258. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  259. # create current_defaults.FlatConfig file if there is none
  260. try:
  261. f = open(self.data_path + '/current_defaults.FlatConfig')
  262. f.close()
  263. except IOError:
  264. App.log.debug('Creating empty current_defaults.FlatConfig')
  265. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  266. json.dump({}, f)
  267. f.close()
  268. # create factory_defaults.FlatConfig file if there is none
  269. try:
  270. f = open(self.data_path + '/factory_defaults.FlatConfig')
  271. f.close()
  272. except IOError:
  273. App.log.debug('Creating empty factory_defaults.FlatConfig')
  274. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  275. json.dump({}, f)
  276. f.close()
  277. # create a recent files json file if there is none
  278. try:
  279. f = open(self.data_path + '/recent.json')
  280. f.close()
  281. except IOError:
  282. App.log.debug('Creating empty recent.json')
  283. f = open(self.data_path + '/recent.json', 'w')
  284. json.dump([], f)
  285. f.close()
  286. # create a recent projects json file if there is none
  287. try:
  288. fp = open(self.data_path + '/recent_projects.json')
  289. fp.close()
  290. except IOError:
  291. App.log.debug('Creating empty recent_projects.json')
  292. fp = open(self.data_path + '/recent_projects.json', 'w')
  293. json.dump([], fp)
  294. fp.close()
  295. # Application directory. CHDIR to it. Otherwise, trying to load
  296. # GUI icons will fail as their path is relative.
  297. # This will fail under cx_freeze ...
  298. self.app_home = os.path.dirname(os.path.realpath(__file__))
  299. App.log.debug("Application path is " + self.app_home)
  300. App.log.debug("Started in " + os.getcwd())
  301. # cx_freeze workaround
  302. if os.path.isfile(self.app_home):
  303. self.app_home = os.path.dirname(self.app_home)
  304. os.chdir(self.app_home)
  305. # #############################################################################
  306. # ##################### CREATE MULTIPROCESSING POOL ###########################
  307. # #############################################################################
  308. self.pool = Pool(processes=cpu_count())
  309. # ##########################################################################
  310. # ################## Setting the Splash Screen #############################
  311. # ##########################################################################
  312. settings = QSettings("Open Source", "FlatCAM")
  313. if settings.contains("splash_screen"):
  314. show_splash = settings.value("splash_screen")
  315. else:
  316. settings.setValue('splash_screen', 1)
  317. # This will write the setting to the platform specific storage.
  318. del settings
  319. show_splash = 1
  320. if show_splash and self.cmd_line_headless != 1:
  321. splash_pix = QtGui.QPixmap('share/splash.png')
  322. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  323. # self.splash.setMask(splash_pix.mask())
  324. # move splashscreen to the current monitor
  325. desktop = QtWidgets.QApplication.desktop()
  326. screen = desktop.screenNumber(QtGui.QCursor.pos())
  327. current_screen_center = desktop.availableGeometry(screen).center()
  328. self.splash.move(current_screen_center - self.splash.rect().center())
  329. self.splash.show()
  330. self.splash.showMessage(_("FlatCAM is initializing ..."),
  331. alignment=Qt.AlignBottom | Qt.AlignLeft,
  332. color=QtGui.QColor("gray"))
  333. else:
  334. show_splash = 0
  335. # #############################################################################
  336. # ##################### Initialize GUI ########################################
  337. # #############################################################################
  338. # FlatCAM colors used in plotting
  339. self.FC_light_green = '#BBF268BF'
  340. self.FC_dark_green = '#006E20BF'
  341. self.FC_light_blue = '#a5a5ffbf'
  342. self.FC_dark_blue = '#0000ffbf'
  343. QtCore.QObject.__init__(self)
  344. self.ui = FlatCAMGUI(self.version, self.beta, self)
  345. settings = QtCore.QSettings("Open Source", "FlatCAM")
  346. if settings.contains("theme"):
  347. theme = settings.value('theme', type=str)
  348. else:
  349. theme = 'white'
  350. if theme == 'white':
  351. self.cursor_color_3D = 'black'
  352. else:
  353. self.cursor_color_3D = 'gray'
  354. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  355. self.ui.final_save.connect(self.final_save)
  356. # #############################################################################
  357. # ############################## Data #########################################
  358. # #############################################################################
  359. self.recent = []
  360. self.recent_projects = []
  361. self.clipboard = QtWidgets.QApplication.clipboard()
  362. self.project_filename = None
  363. self.toggle_units_ignore = False
  364. # self.defaults_form = PreferencesUI()
  365. # when adding entries here read the comments in the method found bellow named:
  366. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  367. self.defaults_form_fields = {
  368. # General App
  369. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  370. "global_graphic_engine": self.ui.general_defaults_form.general_app_group.ge_radio,
  371. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  372. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  373. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  374. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  375. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  376. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  377. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  378. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  379. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  380. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  381. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_spinner,
  382. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  383. "global_bookmarks_limit": self.ui.general_defaults_form.general_app_group.bm_limit_spinner,
  384. # General GUI Preferences
  385. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  386. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  387. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  388. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  389. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  390. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  391. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  392. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  393. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  394. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  395. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  396. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  397. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  398. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  399. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  400. "global_activity_icon": self.ui.general_defaults_form.general_gui_group.activity_combo,
  401. # General GUI Settings
  402. "global_theme": self.ui.general_defaults_form.general_gui_set_group.theme_radio,
  403. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  404. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  405. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  406. "global_systray_icon": self.ui.general_defaults_form.general_gui_set_group.systray_cb,
  407. "global_shell_at_startup": self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb,
  408. "global_project_at_startup": self.ui.general_defaults_form.general_gui_set_group.project_startup_cb,
  409. "global_project_autohide": self.ui.general_defaults_form.general_gui_set_group.project_autohide_cb,
  410. "global_toggle_tooltips": self.ui.general_defaults_form.general_gui_set_group.toggle_tooltips_cb,
  411. "global_delete_confirmation": self.ui.general_defaults_form.general_gui_set_group.delete_conf_cb,
  412. "global_cursor_type": self.ui.general_defaults_form.general_gui_set_group.cursor_radio,
  413. "global_cursor_size": self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry,
  414. # Gerber General
  415. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  416. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  417. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  418. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  419. "gerber_def_units": self.ui.gerber_defaults_form.gerber_gen_group.gerber_units_radio,
  420. "gerber_def_zeros": self.ui.gerber_defaults_form.gerber_gen_group.gerber_zeros_radio,
  421. # Gerber Options
  422. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  423. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  424. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  425. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  426. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  427. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  428. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  429. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  430. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  431. # Gerber Advanced Options
  432. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  433. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  434. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  435. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  436. "gerber_tool_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.tool_type_radio,
  437. "gerber_vtipdia": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipdia_spinner,
  438. "gerber_vtipangle": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipangle_spinner,
  439. "gerber_vcutz": self.ui.gerber_defaults_form.gerber_adv_opt_group.cutz_spinner,
  440. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  441. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  442. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  443. # Gerber Export
  444. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  445. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  446. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  447. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  448. # Gerber Editor
  449. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  450. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  451. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  452. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  453. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  454. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  455. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  456. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  457. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  458. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  459. "gerber_editor_circ_angle":
  460. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  461. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  462. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  463. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  464. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  465. # Excellon General
  466. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  467. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  468. "excellon_format_upper_in":
  469. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  470. "excellon_format_lower_in":
  471. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  472. "excellon_format_upper_mm":
  473. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  474. "excellon_format_lower_mm":
  475. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  476. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  477. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  478. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  479. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  480. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  481. # Excellon Options
  482. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  483. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  484. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.eendz_entry,
  485. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  486. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  487. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  488. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  489. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  490. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  491. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  492. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  493. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  494. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  495. # Excellon Advanced Options
  496. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  497. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  498. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  499. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  500. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  501. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  502. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  503. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  504. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  505. # Excellon Export
  506. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  507. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  508. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  509. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  510. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  511. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  512. # Excellon Editor
  513. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  514. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  515. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  516. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  517. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  518. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  519. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  520. "excellon_editor_circ_angle":
  521. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  522. # Excellon Slots
  523. "excellon_editor_slot_direction":
  524. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  525. "excellon_editor_slot_angle":
  526. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  527. "excellon_editor_slot_length":
  528. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  529. # Excellon Slots
  530. "excellon_editor_slot_array_size":
  531. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  532. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  533. "excellon_editor_slot_lin_pitch":
  534. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  535. "excellon_editor_slot_lin_angle":
  536. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  537. "excellon_editor_slot_circ_dir":
  538. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  539. "excellon_editor_slot_circ_angle":
  540. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  541. # Geometry General
  542. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  543. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  544. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  545. # Geometry Options
  546. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  547. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  548. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  549. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  550. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  551. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  552. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  553. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  554. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  555. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  556. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.gendz_entry,
  557. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  558. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  559. # Geometry Advanced Options
  560. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  561. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  562. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  563. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  564. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  565. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  566. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  567. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  568. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  569. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  570. # Geometry Editor
  571. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  572. "geometry_editor_milling_type": self.ui.geometry_defaults_form.geometry_editor_group.milling_type_radio,
  573. # CNCJob General
  574. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  575. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  576. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  577. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  578. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  579. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  580. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  581. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  582. # CNC Job Options
  583. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  584. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  585. # CNC Job Advanced Options
  586. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  587. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  588. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  589. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  590. # NCC Tool
  591. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  592. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  593. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  594. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  595. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  596. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  597. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  598. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  599. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  600. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  601. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  602. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  603. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  604. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  605. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  606. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  607. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  608. # CutOut Tool
  609. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  610. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  611. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  612. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  613. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  614. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  615. # Paint Area Tool
  616. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  617. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  618. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  619. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  620. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  621. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  622. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  623. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  624. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  625. # 2-sided Tool
  626. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  627. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  628. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  629. # Film Tool
  630. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  631. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  632. "tools_film_scale_stroke": self.ui.tools_defaults_form.tools_film_group.film_scale_stroke_entry,
  633. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  634. "tools_film_scale_cb": self.ui.tools_defaults_form.tools_film_group.film_scale_cb,
  635. "tools_film_scale_x_entry": self.ui.tools_defaults_form.tools_film_group.film_scalex_entry,
  636. "tools_film_scale_y_entry": self.ui.tools_defaults_form.tools_film_group.film_scaley_entry,
  637. "tools_film_skew_cb": self.ui.tools_defaults_form.tools_film_group.film_skew_cb,
  638. "tools_film_skew_x_entry": self.ui.tools_defaults_form.tools_film_group.film_skewx_entry,
  639. "tools_film_skew_y_entry": self.ui.tools_defaults_form.tools_film_group.film_skewy_entry,
  640. "tools_film_skew_ref_radio": self.ui.tools_defaults_form.tools_film_group.film_skew_reference,
  641. "tools_film_mirror_cb": self.ui.tools_defaults_form.tools_film_group.film_mirror_cb,
  642. "tools_film_mirror_axis_radio": self.ui.tools_defaults_form.tools_film_group.film_mirror_axis,
  643. # Panelize Tool
  644. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  645. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  646. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  647. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  648. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  649. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  650. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  651. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  652. # Calculators Tool
  653. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  654. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  655. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  656. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  657. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  658. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  659. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  660. # Transformations Tool
  661. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  662. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  663. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  664. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  665. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  666. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  667. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  668. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  669. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  670. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  671. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  672. # SolderPaste Dispensing Tool
  673. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  674. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  675. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  676. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  677. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  678. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  679. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  680. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  681. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  682. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  683. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  684. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  685. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  686. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  687. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  688. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  689. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  690. # ###################################################################################
  691. # ################################ TOOLS 2 ##########################################
  692. # ###################################################################################
  693. # Optimal Tool
  694. "tools_opt_precision": self.ui.tools2_defaults_form.tools2_optimal_group.precision_sp,
  695. # Check Rules Tool
  696. "tools_cr_trace_size": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_cb,
  697. "tools_cr_trace_size_val": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_entry,
  698. "tools_cr_c2c": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_cb,
  699. "tools_cr_c2c_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_entry,
  700. "tools_cr_c2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_cb,
  701. "tools_cr_c2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_entry,
  702. "tools_cr_s2s": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_cb,
  703. "tools_cr_s2s_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_entry,
  704. "tools_cr_s2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_cb,
  705. "tools_cr_s2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_entry,
  706. "tools_cr_s2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_cb,
  707. "tools_cr_s2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_entry,
  708. "tools_cr_sm2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_cb,
  709. "tools_cr_sm2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_entry,
  710. "tools_cr_ri": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_cb,
  711. "tools_cr_ri_val": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_entry,
  712. "tools_cr_h2h": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_cb,
  713. "tools_cr_h2h_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_entry,
  714. "tools_cr_dh": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_cb,
  715. "tools_cr_dh_val": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_entry,
  716. # QRCode Tool
  717. "tools_qrcode_version": self.ui.tools2_defaults_form.tools2_qrcode_group.version_entry,
  718. "tools_qrcode_error": self.ui.tools2_defaults_form.tools2_qrcode_group.error_radio,
  719. "tools_qrcode_box_size": self.ui.tools2_defaults_form.tools2_qrcode_group.bsize_entry,
  720. "tools_qrcode_border_size": self.ui.tools2_defaults_form.tools2_qrcode_group.border_size_entry,
  721. "tools_qrcode_qrdata": self.ui.tools2_defaults_form.tools2_qrcode_group.text_data,
  722. "tools_qrcode_polarity": self.ui.tools2_defaults_form.tools2_qrcode_group.pol_radio,
  723. "tools_qrcode_rounded": self.ui.tools2_defaults_form.tools2_qrcode_group.bb_radio,
  724. "tools_qrcode_fill_color": self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry,
  725. "tools_qrcode_back_color": self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry,
  726. "tools_qrcode_sel_limit": self.ui.tools2_defaults_form.tools2_qrcode_group.sel_limit_entry,
  727. # Copper Fill Tool
  728. "tools_copperfill_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_entry,
  729. "tools_copperfill_margin": self.ui.tools2_defaults_form.tools2_cfill_group.margin_entry,
  730. "tools_copperfill_reference": self.ui.tools2_defaults_form.tools2_cfill_group.reference_radio,
  731. "tools_copperfill_box_type": self.ui.tools2_defaults_form.tools2_cfill_group.bbox_type_radio,
  732. "tools_copperfill_circle_steps": self.ui.tools2_defaults_form.tools2_cfill_group.circlesteps_entry,
  733. # Utilities
  734. # File associations
  735. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  736. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  737. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  738. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  739. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  740. }
  741. # ############################
  742. # ### LOAD POSTPROCESSORS ####
  743. # ############################
  744. self.postprocessors = load_postprocessors(self)
  745. for name in list(self.postprocessors.keys()):
  746. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  747. if name.partition('_')[0] == 'Paste':
  748. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  749. continue
  750. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  751. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  752. if name == 'hpgl':
  753. continue
  754. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  755. # ############################
  756. # ### LOAD LANGUAGES ####
  757. # ############################
  758. self.languages = fcTranslate.load_languages()
  759. for name in sorted(self.languages.values()):
  760. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  761. # #################################################################################
  762. # #################### DEFAULTS - PREFERENCES STORAGE #############################
  763. # #################################################################################
  764. self.defaults = LoudDict()
  765. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  766. self.defaults.update({
  767. # Global APP Preferences
  768. "first_run": True,
  769. "units": "IN",
  770. "global_serial": 0,
  771. "global_stats": {},
  772. "global_tabs_detachable": True,
  773. "global_graphic_engine": '3D',
  774. "global_app_level": 'b',
  775. "global_portable": False,
  776. "global_language": 'English',
  777. "global_version_check": True,
  778. "global_send_stats": True,
  779. "global_pan_button": '2',
  780. "global_mselect_key": 'Control',
  781. "global_project_at_startup": False,
  782. "global_systray_icon": True,
  783. "global_project_autohide": True,
  784. "global_toggle_tooltips": True,
  785. "global_worker_number": 2,
  786. "global_tolerance": 0.0002,
  787. "global_open_style": True,
  788. "global_delete_confirmation": True,
  789. "global_compression_level": 3,
  790. "global_save_compressed": True,
  791. # Global GUI Preferences
  792. "global_gridx": 0.0393701,
  793. "global_gridy": 0.0393701,
  794. "global_snap_max": 0.001968504,
  795. "global_workspace": False,
  796. "global_workspaceT": "A4P",
  797. "global_grid_context_menu": {
  798. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  799. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  800. },
  801. "global_plot_fill": '#BBF268BF',
  802. "global_plot_line": '#006E20BF',
  803. "global_sel_fill": '#a5a5ffbf',
  804. "global_sel_line": '#0000ffbf',
  805. "global_alt_sel_fill": '#BBF268BF',
  806. "global_alt_sel_line": '#006E20BF',
  807. "global_draw_color": '#FF0000',
  808. "global_sel_draw_color": '#0000FF',
  809. "global_proj_item_color": '#000000',
  810. "global_proj_item_dis_color": '#b7b7cb',
  811. "global_activity_icon": 'Ball green',
  812. "global_toolbar_view": 511,
  813. "global_background_timeout": 300000, # Default value is 5 minutes
  814. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  815. # (python trace only for unknown errors),
  816. # 1 = show trace(show trace always),
  817. # 2 = (For the future).
  818. # Persistence
  819. "global_last_folder": None,
  820. "global_last_save_folder": None,
  821. # Default window geometry
  822. "global_def_win_x": 100,
  823. "global_def_win_y": 100,
  824. "global_def_win_w": 1024,
  825. "global_def_win_h": 650,
  826. "global_def_notebook_width": 1,
  827. # Constants...
  828. "global_defaults_save_period_ms": 20000, # Time between default saves.
  829. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  830. "global_shell_at_startup": False, # Show the shell at startup.
  831. "global_recent_limit": 10, # Max. items in recent list.
  832. "global_bookmarks": dict(),
  833. "global_bookmarks_limit": 10,
  834. "fit_key": 'V',
  835. "zoom_out_key": '-',
  836. "zoom_in_key": '=',
  837. "grid_toggle_key": 'G',
  838. "global_zoom_ratio": 1.5,
  839. "global_point_clipboard_format": "(%.4f, %.4f)",
  840. "global_zdownrate": None,
  841. # General GUI Settings
  842. "global_theme": 'white',
  843. "global_hover": False,
  844. "global_selection_shape": True,
  845. "global_layout": "compact",
  846. "global_cursor_type": "small",
  847. "global_cursor_size": 20,
  848. # Gerber General
  849. "gerber_plot": True,
  850. "gerber_solid": True,
  851. "gerber_multicolored": False,
  852. "gerber_circle_steps": 128,
  853. "gerber_use_buffer_for_union": True,
  854. "gerber_def_units": 'IN',
  855. "gerber_def_zeros": 'L',
  856. # Gerber Options
  857. "gerber_isotooldia": 0.00787402,
  858. "gerber_isopasses": 1,
  859. "gerber_isooverlap": 0.00393701,
  860. "gerber_milling_type": "cl",
  861. "gerber_combine_passes": False,
  862. "gerber_noncoppermargin": 0.00393701,
  863. "gerber_noncopperrounded": False,
  864. "gerber_bboxmargin": 0.00393701,
  865. "gerber_bboxrounded": False,
  866. # Gerber Advanced Options
  867. "gerber_aperture_display": False,
  868. "gerber_aperture_scale_factor": 1.0,
  869. "gerber_aperture_buffer_factor": 0.0,
  870. "gerber_follow": False,
  871. "gerber_tool_type": 'circular',
  872. "gerber_vtipdia": 0.1,
  873. "gerber_vtipangle": 30,
  874. "gerber_vcutz": -0.05,
  875. "gerber_buffering": "full",
  876. "gerber_simplification": False,
  877. "gerber_simp_tolerance": 0.0005,
  878. # Gerber Export
  879. "gerber_exp_units": 'IN',
  880. "gerber_exp_integer": 2,
  881. "gerber_exp_decimals": 4,
  882. "gerber_exp_zeros": 'L',
  883. # Gerber Editor
  884. "gerber_editor_sel_limit": 30,
  885. "gerber_editor_newcode": 10,
  886. "gerber_editor_newsize": 0.031496,
  887. "gerber_editor_newtype": 'C',
  888. "gerber_editor_newdim": "0.5, 0.5",
  889. "gerber_editor_array_size": 5,
  890. "gerber_editor_lin_axis": 'X',
  891. "gerber_editor_lin_pitch": 1,
  892. "gerber_editor_lin_angle": 0.0,
  893. "gerber_editor_circ_dir": 'CW',
  894. "gerber_editor_circ_angle": 0.0,
  895. "gerber_editor_scale_f": 1.0,
  896. "gerber_editor_buff_f": 0.01,
  897. "gerber_editor_ma_low": 0.0,
  898. "gerber_editor_ma_high": 1.0,
  899. # Excellon General
  900. "excellon_plot": True,
  901. "excellon_solid": True,
  902. "excellon_format_upper_in": 2,
  903. "excellon_format_lower_in": 4,
  904. "excellon_format_upper_mm": 3,
  905. "excellon_format_lower_mm": 3,
  906. "excellon_zeros": "L",
  907. "excellon_units": "INCH",
  908. "excellon_update": True,
  909. "excellon_optimization_type": 'B',
  910. "excellon_search_time": 3,
  911. # Excellon Options
  912. "excellon_drillz": -0.0590551,
  913. "excellon_travelz": 0.0787402,
  914. "excellon_endz": 0.5,
  915. "excellon_feedrate": 3.14961,
  916. "excellon_spindlespeed": None,
  917. "excellon_dwell": False,
  918. "excellon_dwelltime": 1,
  919. "excellon_toolchange": False,
  920. "excellon_toolchangez": 0.5,
  921. "excellon_ppname_e": 'default',
  922. "excellon_tooldia": 0.0314961,
  923. "excellon_slot_tooldia": 0.0708661,
  924. "excellon_gcode_type": "drills",
  925. # Excellon Advanced Options
  926. "excellon_offset": 0.0,
  927. "excellon_toolchangexy": "0.0, 0.0",
  928. "excellon_startz": None,
  929. "excellon_feedrate_rapid": 31.4961,
  930. "excellon_z_pdepth": -0.02,
  931. "excellon_feedrate_probe": 3.14961,
  932. "excellon_spindledir": 'CW',
  933. "excellon_f_plunge": False,
  934. "excellon_f_retract": False,
  935. # Excellon Export
  936. "excellon_exp_units": 'INCH',
  937. "excellon_exp_format": 'ndec',
  938. "excellon_exp_integer": 2,
  939. "excellon_exp_decimals": 4,
  940. "excellon_exp_zeros": 'LZ',
  941. "excellon_exp_slot_type": 'routing',
  942. # Excellon Editor
  943. "excellon_editor_sel_limit": 30,
  944. "excellon_editor_newdia": 0.039,
  945. "excellon_editor_array_size": 5,
  946. "excellon_editor_lin_dir": 'X',
  947. "excellon_editor_lin_pitch": 0.1,
  948. "excellon_editor_lin_angle": 0.0,
  949. "excellon_editor_circ_dir": 'CW',
  950. "excellon_editor_circ_angle": 12,
  951. # Excellon Slots
  952. "excellon_editor_slot_direction": 'X',
  953. "excellon_editor_slot_angle": 0.0,
  954. "excellon_editor_slot_length": 5.0,
  955. # Excellon Slot Array
  956. "excellon_editor_slot_array_size": 5,
  957. "excellon_editor_slot_lin_dir": 'X',
  958. "excellon_editor_slot_lin_pitch": 0.1,
  959. "excellon_editor_slot_lin_angle": 0.0,
  960. "excellon_editor_slot_circ_dir": 'CW',
  961. "excellon_editor_slot_circ_angle": 0.0,
  962. # Geometry General
  963. "geometry_plot": True,
  964. "geometry_circle_steps": 128,
  965. "geometry_cnctooldia": "0.0944882",
  966. # Geometry Options
  967. "geometry_cutz": -0.0944882,
  968. "geometry_vtipdia": 0.1,
  969. "geometry_vtipangle": 30,
  970. "geometry_multidepth": False,
  971. "geometry_depthperpass": 0.0314961,
  972. "geometry_travelz": 0.0787402,
  973. "geometry_toolchange": False,
  974. "geometry_toolchangez": 0.5,
  975. "geometry_endz": 0.5,
  976. "geometry_feedrate": 3.14961,
  977. "geometry_feedrate_z": 3.14961,
  978. "geometry_spindlespeed": None,
  979. "geometry_dwell": False,
  980. "geometry_dwelltime": 1,
  981. "geometry_ppname_g": 'default',
  982. # Geometry Advanced Options
  983. "geometry_toolchangexy": "0.0, 0.0",
  984. "geometry_startz": None,
  985. "geometry_feedrate_rapid": 3.14961,
  986. "geometry_extracut": False,
  987. "geometry_z_pdepth": -0.02,
  988. "geometry_f_plunge": False,
  989. "geometry_spindledir": 'CW',
  990. "geometry_feedrate_probe": 3.14961,
  991. "geometry_segx": 0.0,
  992. "geometry_segy": 0.0,
  993. # Geometry Editor
  994. "geometry_editor_sel_limit": 30,
  995. "geometry_editor_milling_type": "cl",
  996. # CNC Job General
  997. "cncjob_plot": True,
  998. "cncjob_plot_kind": 'all',
  999. "cncjob_annotation": True,
  1000. "cncjob_tooldia": 0.0393701,
  1001. "cncjob_coords_type": "G90",
  1002. "cncjob_coords_decimals": 4,
  1003. "cncjob_fr_decimals": 2,
  1004. "cncjob_steps_per_circle": 128,
  1005. # CNC Job Options
  1006. "cncjob_prepend": "",
  1007. "cncjob_append": "",
  1008. # CNC Job Advanced Options
  1009. "cncjob_toolchange_macro": "",
  1010. "cncjob_toolchange_macro_enable": False,
  1011. "cncjob_annotation_fontsize": 9,
  1012. "cncjob_annotation_fontcolor": '#990000',
  1013. # NCC Tool
  1014. "tools_ncctools": "0.0393701, 0.019685",
  1015. "tools_nccorder": 'rev',
  1016. "tools_nccoverlap": 0.015748,
  1017. "tools_nccmargin": 0.0393701,
  1018. "tools_nccmethod": "seed",
  1019. "tools_nccconnect": True,
  1020. "tools_ncccontour": True,
  1021. "tools_nccrest": False,
  1022. "tools_ncc_offset_choice": False,
  1023. "tools_ncc_offset_value": 0.0000,
  1024. "tools_nccref": 'itself',
  1025. "tools_ncc_plotting": 'normal',
  1026. "tools_nccmilling_type": 'cl',
  1027. "tools_ncctool_type": 'V',
  1028. "tools_ncccutz": -0.001968504,
  1029. "tools_ncctipdia": 0.00393701,
  1030. "tools_ncctipangle": 30,
  1031. # Cutout Tool
  1032. "tools_cutouttooldia": 0.0944882,
  1033. "tools_cutoutkind": "single",
  1034. "tools_cutoutmargin": 0.00393701,
  1035. "tools_cutoutgapsize": 0.15748,
  1036. "tools_gaps_ff": "4",
  1037. "tools_cutout_convexshape": False,
  1038. # Paint Tool
  1039. "tools_painttooldia": 0.023622,
  1040. "tools_paintorder": 'rev',
  1041. "tools_paintoverlap": 0.015748,
  1042. "tools_paintmargin": 0.0,
  1043. "tools_paintmethod": "seed",
  1044. "tools_selectmethod": "all",
  1045. "tools_pathconnect": True,
  1046. "tools_paintcontour": True,
  1047. "tools_paint_plotting": 'normal',
  1048. # 2-Sided Tool
  1049. "tools_2sided_mirror_axis": "X",
  1050. "tools_2sided_axis_loc": "point",
  1051. "tools_2sided_drilldia": 0.11811,
  1052. # Film Tool
  1053. "tools_film_type": 'neg',
  1054. "tools_film_boundary": 0.0393701,
  1055. "tools_film_scale_stroke": 0,
  1056. "tools_film_color": '#000000',
  1057. "tools_film_scale_cb": False,
  1058. "tools_film_scale_x_entry": 1.0,
  1059. "tools_film_scale_y_entry": 1.0,
  1060. "tools_film_skew_cb": False,
  1061. "tools_film_skew_x_entry": 0.0,
  1062. "tools_film_skew_y_entry": 0.0,
  1063. "tools_film_skew_ref_radio": 'bottomleft',
  1064. "tools_film_mirror_cb": False,
  1065. "tools_film_mirror_axis_radio": 'none',
  1066. # Panel Tool
  1067. "tools_panelize_spacing_columns": 0,
  1068. "tools_panelize_spacing_rows": 0,
  1069. "tools_panelize_columns": 1,
  1070. "tools_panelize_rows": 1,
  1071. "tools_panelize_constrain": False,
  1072. "tools_panelize_constrainx": 200.0,
  1073. "tools_panelize_constrainy": 290.0,
  1074. "tools_panelize_panel_type": 'gerber',
  1075. # Calculators Tool
  1076. "tools_calc_vshape_tip_dia": 0.007874,
  1077. "tools_calc_vshape_tip_angle": 30,
  1078. "tools_calc_vshape_cut_z": 0.000787,
  1079. "tools_calc_electro_length": 10.0,
  1080. "tools_calc_electro_width": 10.0,
  1081. "tools_calc_electro_cdensity": 13.0,
  1082. "tools_calc_electro_growth": 10.0,
  1083. # Transform Tool
  1084. "tools_transform_rotate": 90,
  1085. "tools_transform_skew_x": 0.0,
  1086. "tools_transform_skew_y": 0.0,
  1087. "tools_transform_scale_x": 1.0,
  1088. "tools_transform_scale_y": 1.0,
  1089. "tools_transform_scale_link": True,
  1090. "tools_transform_scale_reference": True,
  1091. "tools_transform_offset_x": 0.0,
  1092. "tools_transform_offset_y": 0.0,
  1093. "tools_transform_mirror_reference": False,
  1094. "tools_transform_mirror_point": (0, 0),
  1095. # SolderPaste Tool
  1096. "tools_solderpaste_tools": "0.0393701, 0.011811",
  1097. "tools_solderpaste_new": 0.011811,
  1098. "tools_solderpaste_z_start": 0.00019685039,
  1099. "tools_solderpaste_z_dispense": 0.00393701,
  1100. "tools_solderpaste_z_stop": 0.00019685039,
  1101. "tools_solderpaste_z_travel": 0.00393701,
  1102. "tools_solderpaste_z_toolchange": 0.0393701,
  1103. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  1104. "tools_solderpaste_frxy": 3.0,
  1105. "tools_solderpaste_frz": 3.0,
  1106. "tools_solderpaste_frz_dispense": 0.0393701,
  1107. "tools_solderpaste_speedfwd": 20,
  1108. "tools_solderpaste_dwellfwd": 1,
  1109. "tools_solderpaste_speedrev": 10,
  1110. "tools_solderpaste_dwellrev": 1,
  1111. "tools_solderpaste_pp": 'Paste_1',
  1112. # Subtract Tool
  1113. "tools_sub_close_paths": True,
  1114. # ###################################################################################
  1115. # ################################ TOOLS 2 ##########################################
  1116. # ###################################################################################
  1117. # Optimal Tool
  1118. "tools_opt_precision": 4,
  1119. # Check Rules Tool
  1120. "tools_cr_trace_size": True,
  1121. "tools_cr_trace_size_val": 0.01,
  1122. "tools_cr_c2c": True,
  1123. "tools_cr_c2c_val": 0.01,
  1124. "tools_cr_c2o": True,
  1125. "tools_cr_c2o_val": 0.03937,
  1126. "tools_cr_s2s": True,
  1127. "tools_cr_s2s_val": 0.01,
  1128. "tools_cr_s2sm": True,
  1129. "tools_cr_s2sm_val": 0.01,
  1130. "tools_cr_s2o": True,
  1131. "tools_cr_s2o_val": 0.03937,
  1132. "tools_cr_sm2sm": True,
  1133. "tools_cr_sm2sm_val": 0.01,
  1134. "tools_cr_ri": True,
  1135. "tools_cr_ri_val": 0.015,
  1136. "tools_cr_h2h": True,
  1137. "tools_cr_h2h_val": 0.015,
  1138. "tools_cr_dh": True,
  1139. "tools_cr_dh_val": 0.011811,
  1140. # QRCode Tool
  1141. "tools_qrcode_version": 1,
  1142. "tools_qrcode_error": 'L',
  1143. "tools_qrcode_box_size": 3,
  1144. "tools_qrcode_border_size": 4,
  1145. "tools_qrcode_qrdata": '',
  1146. "tools_qrcode_polarity": 'pos',
  1147. "tools_qrcode_rounded": 's',
  1148. "tools_qrcode_fill_color": '#000000',
  1149. "tools_qrcode_back_color": '#FFFFFF',
  1150. "tools_qrcode_sel_limit": 330,
  1151. # Copper Fill Tool
  1152. "tools_copperfill_clearance": 0.01,
  1153. "tools_copperfill_margin": 0.039,
  1154. "tools_copperfill_reference": 'itself',
  1155. "tools_copperfill_box_type": 'rect',
  1156. "tools_copperfill_circle_steps": 128,
  1157. # Utilities
  1158. # file associations
  1159. "fa_excellon": 'drd, drl, exc, ncd, tap, xln',
  1160. "fa_gcode": 'cnc, din, dnc, ecs, eia, fan, fgc, fnc, gc, gcd, gcode, h, hnc, i, min, mpf, mpr, nc, ncc, '
  1161. 'ncg, ncp, out, plt, ply, rol, sbp, tap, xpi',
  1162. "fa_gerber": 'art, bot, bsm, cmp, crc, crs, dim, g4, gb0, gb1, gb2, gb3, gb5, gb6, gb7, gb8, gb9, gbd, '
  1163. 'gbl, gbo, gbp, gbr, gbs, gdo, ger, gko, gm1, gm2, gm3, grb, gtl, gto, gtp, gts, ly15, ly2, '
  1164. 'mil, pho, plc, pls, smb, smt, sol, spb, spt, ssb, sst, stc, sts, top, tsm',
  1165. # Keyword list
  1166. "util_autocomplete_keywords": 'Desktop, Documents, FlatConfig, FlatPrj, Marius, My Documents, Paste_1, '
  1167. 'Repetier, Roland_MDX_20, Users, Toolchange_Custom, Toolchange_Probe_MACH3, '
  1168. 'Toolchange_manual, Users, all, angle_x, angle_y, axis, auto, axisoffset, '
  1169. 'box, center_x, center_y, columns, combine, connect, contour, default, '
  1170. 'depthperpass, dia, diatol, dist, drilled_dias, drillz, dwell, dwelltime, '
  1171. 'feedrate_z, grbl_11, grbl_laser, gridoffsety, gridx, gridy, has_offset, '
  1172. 'holes, hpgl, iso_type, line_xyz, margin, marlin, method, milled_dias, '
  1173. 'minoffset, multidepth, name, offset, opt_type, order, outname, overlap, '
  1174. 'passes, postamble, pp, ppname_e, ppname_g, preamble, radius, ref, rest, '
  1175. 'rows, shellvar_, scale_factor, spacing_columns, spacing_rows, spindlespeed, '
  1176. 'toolchange_xy, tooldia, use_threads, value, x, x0, x1, y, y0, y1, z_cut, '
  1177. 'z_move',
  1178. "script_autocompleter": True,
  1179. "script_text": "",
  1180. "script_plot": True,
  1181. "script_source_file": "",
  1182. "document_autocompleter": False,
  1183. "document_text": "",
  1184. "document_plot": True,
  1185. "document_source_file": "",
  1186. "document_font_color": '#000000',
  1187. "document_sel_color": '#0055ff',
  1188. "document_font_size": 6,
  1189. "document_tab_size": 80,
  1190. })
  1191. # ############################################################
  1192. # ############### Load defaults from file ####################
  1193. # ############################################################
  1194. if user_defaults:
  1195. self.load_defaults(filename='current_defaults')
  1196. # #############################################################
  1197. # ############## APPLY APP LANGUAGE ###########################
  1198. # #############################################################
  1199. ret_val = fcTranslate.apply_language('strings')
  1200. if ret_val == "no language":
  1201. self.inform.emit('[ERROR] %s' %
  1202. _("Could not find the Language files. The App strings are missing."))
  1203. log.debug("Could not find the Language files. The App strings are missing.")
  1204. else:
  1205. # make the current language the current selection on the language combobox
  1206. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1207. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1208. # ##############################################################
  1209. # ################# CREATE UNIQUE SERIAL NUMBER ################
  1210. # ##############################################################
  1211. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1212. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1213. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  1214. self.save_defaults(silent=True, first_time=True)
  1215. self.propagate_defaults(silent=True)
  1216. self.restore_main_win_geom()
  1217. # def auto_save_defaults():
  1218. # try:
  1219. # self.save_defaults(silent=True)
  1220. # self.propagate_defaults(silent=True)
  1221. # finally:
  1222. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1223. # the following lines activates automatic defaults save
  1224. # if user_defaults:
  1225. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1226. # self.options_form = PreferencesUI()
  1227. self.options_form_fields = {
  1228. "units": self.ui.general_options_form.general_app_group.units_radio,
  1229. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  1230. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  1231. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  1232. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  1233. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  1234. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  1235. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  1236. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  1237. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  1238. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  1239. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  1240. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  1241. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  1242. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  1243. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  1244. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  1245. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  1246. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  1247. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1248. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1249. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  1250. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  1251. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  1252. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  1253. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  1254. "excellon_endz": self.ui.excellon_options_form.excellon_opt_group.eendz_entry,
  1255. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  1256. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  1257. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  1258. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  1259. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  1260. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  1261. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  1262. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  1263. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1264. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  1265. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  1266. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  1267. "excellon_spindledir": self.ui.excellon_options_form.excellon_adv_opt_group.spindledir_radio,
  1268. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  1269. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  1270. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  1271. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  1272. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  1273. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  1274. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  1275. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  1276. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  1277. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  1278. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  1279. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  1280. "geometry_endz": self.ui.geometry_options_form.geometry_opt_group.gendz_entry,
  1281. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  1282. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  1283. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  1284. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  1285. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1286. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  1287. "geometry_spindledir": self.ui.geometry_options_form.geometry_adv_opt_group.spindledir_radio,
  1288. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  1289. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  1290. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  1291. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  1292. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  1293. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  1294. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  1295. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  1296. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  1297. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  1298. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  1299. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  1300. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  1301. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  1302. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  1303. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  1304. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  1305. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  1306. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  1307. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  1308. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  1309. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  1310. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  1311. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  1312. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  1313. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  1314. "tools_film_scale_stroke": self.ui.tools_options_form.tools_film_group.film_scale_stroke_entry,
  1315. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  1316. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  1317. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  1318. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  1319. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  1320. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  1321. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  1322. }
  1323. for name in list(self.postprocessors.keys()):
  1324. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1325. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1326. self.options = LoudDict()
  1327. self.options.set_change_callback(self.on_options_dict_change)
  1328. self.options.update({
  1329. "units": "IN",
  1330. "global_gridx": 1.0,
  1331. "global_gridy": 1.0,
  1332. "global_snap_max": 0.05,
  1333. "global_background_timeout": 300000, # Default value is 5 minutes
  1334. "global_verbose_error_level": 0, # Shell verbosity:
  1335. # 0 = default(python trace only for unknown errors),
  1336. # 1 = show trace(show trace allways), 2 = (For the future).
  1337. "gerber_plot": True,
  1338. "gerber_solid": True,
  1339. "gerber_multicolored": False,
  1340. "gerber_isotooldia": 0.016,
  1341. "gerber_isopasses": 1,
  1342. "gerber_isooverlap": 0.15,
  1343. "gerber_combine_passes": True,
  1344. "gerber_noncoppermargin": 0.0,
  1345. "gerber_noncopperrounded": False,
  1346. "gerber_bboxmargin": 0.0,
  1347. "gerber_bboxrounded": False,
  1348. "excellon_plot": True,
  1349. "excellon_solid": False,
  1350. "excellon_format_upper_in": 2,
  1351. "excellon_format_lower_in": 4,
  1352. "excellon_format_upper_mm": 3,
  1353. "excellon_format_lower_mm": 3,
  1354. "excellon_units": 'INCH',
  1355. "excellon_optimization_type": 'B',
  1356. "excellon_search_time": 3,
  1357. "excellon_zeros": "L",
  1358. "excellon_drillz": -0.1,
  1359. "excellon_travelz": 0.1,
  1360. "excellon_feedrate": 3.0,
  1361. "excellon_feedrate_rapid": 3.0,
  1362. "excellon_spindlespeed": None,
  1363. "excellon_spindledir": 'CW',
  1364. "excellon_dwell": True,
  1365. "excellon_dwelltime": 1000,
  1366. "excellon_toolchange": False,
  1367. "excellon_toolchangez": 1.0,
  1368. "excellon_toolchangexy": "0.0, 0.0",
  1369. "excellon_tooldia": 0.016,
  1370. "excellon_ppname_e": 'default',
  1371. "excellon_f_plunge": False,
  1372. "excellon_startz": None,
  1373. "excellon_endz": 2.0,
  1374. "geometry_plot": True,
  1375. "geometry_segx": 0.0,
  1376. "geometry_segy": 0.0,
  1377. "geometry_cutz": -0.002,
  1378. "geometry_vtipdia": 0.1,
  1379. "geometry_vtipangle": 30,
  1380. "geometry_travelz": 0.1,
  1381. "geometry_feedrate": 3.0,
  1382. "geometry_feedrate_z": 3.0,
  1383. "geometry_feedrate_rapid": 3.0,
  1384. "geometry_spindlespeed": None,
  1385. "geometry_spindledir": 'CW',
  1386. "geometry_dwell": True,
  1387. "geometry_dwelltime": 1000,
  1388. "geometry_cnctooldia": 0.016,
  1389. "geometry_toolchange": False,
  1390. "geometry_toolchangez": 2.0,
  1391. "geometry_toolchangexy": "0.0, 0.0",
  1392. "geometry_startz": None,
  1393. "geometry_endz": 2.0,
  1394. "geometry_ppname_g": "default",
  1395. "geometry_f_plunge": False,
  1396. "geometry_depthperpass": 0.002,
  1397. "geometry_multidepth": False,
  1398. "geometry_extracut": False,
  1399. "cncjob_plot": True,
  1400. "cncjob_tooldia": 0.016,
  1401. "cncjob_prepend": "",
  1402. "cncjob_append": "",
  1403. "tools_ncctools": "1.0, 0.5",
  1404. "tools_nccoverlap": 0.4,
  1405. "tools_nccmargin": 1,
  1406. "tools_cutouttooldia": 0.07,
  1407. "tools_cutoutmargin": 0.1,
  1408. "tools_cutoutgapsize": 0.15,
  1409. "tools_gaps_ff": "8",
  1410. "tools_painttooldia": 0.07,
  1411. "tools_paintoverlap": 0.15,
  1412. "tools_paintmargin": 0.0,
  1413. "tools_paintmethod": "seed",
  1414. "tools_selectmethod": "single",
  1415. "tools_pathconnect": True,
  1416. "tools_paintcontour": True,
  1417. "tools_2sided_mirror_axis": "X",
  1418. "tools_2sided_axis_loc": 'point',
  1419. "tools_2sided_drilldia": 1,
  1420. "tools_film_type": 'neg',
  1421. "tools_film_boundary": 1,
  1422. "tools_film_scale_stroke": 0,
  1423. "tools_panelize_spacing_columns": 0,
  1424. "tools_panelize_spacing_rows": 0,
  1425. "tools_panelize_columns": 1,
  1426. "tools_panelize_rows": 1,
  1427. "tools_panelize_constrain": False,
  1428. "tools_panelize_constrainx": 0.0,
  1429. "tools_panelize_constrainy": 0.0,
  1430. "script_text": "",
  1431. "script_plot": False,
  1432. "script_source_file": "",
  1433. "document_text": "",
  1434. "document_plot": False,
  1435. "document_source_file": "",
  1436. })
  1437. # ----------------------------------------------------------------------------------------------------
  1438. # Update the self.options from the self.defaults
  1439. # The self.defaults holds the application defaults while the self.options holds the object defaults
  1440. # -----------------------------------------------------------------------------------------------------
  1441. self.options.update(self.defaults) # Copy app defaults to project options
  1442. self.gen_form = None
  1443. self.ger_form = None
  1444. self.exc_form = None
  1445. self.geo_form = None
  1446. self.cnc_form = None
  1447. self.tools_form = None
  1448. self.tools2_form = None
  1449. self.fa_form = None
  1450. self.on_options_combo_change(0) # Will show the initial form
  1451. # ################################
  1452. # -----------------------------------------------------------------------------------------------------
  1453. # Initialize the color box's color in Preferences -> Global -> Color
  1454. # -----------------------------------------------------------------------------------------------------
  1455. # Init Plot Colors
  1456. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  1457. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  1458. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  1459. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1460. int(self.defaults['global_plot_fill'][7:9], 16))
  1461. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1462. int(self.defaults['global_plot_fill'][7:9], 16))
  1463. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1464. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1465. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1466. # Init Left-Right Selection colors
  1467. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1468. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1469. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1470. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1471. int(self.defaults['global_sel_fill'][7:9], 16))
  1472. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1473. int(self.defaults['global_sel_fill'][7:9], 16))
  1474. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1475. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1476. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1477. # Init Right-Left Selection colors
  1478. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1479. self.defaults['global_alt_sel_fill'])
  1480. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1481. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1482. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1483. int(self.defaults['global_sel_fill'][7:9], 16))
  1484. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1485. int(self.defaults['global_sel_fill'][7:9], 16))
  1486. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1487. self.defaults['global_alt_sel_line'])
  1488. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1489. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1490. # Init Draw color and Selection Draw Color
  1491. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1492. self.defaults['global_draw_color'])
  1493. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1494. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1495. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1496. self.defaults['global_sel_draw_color'])
  1497. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1498. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1499. # Init Project Items color
  1500. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1501. self.defaults['global_proj_item_color'])
  1502. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1503. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1504. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1505. self.defaults['global_proj_item_dis_color'])
  1506. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1507. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1508. # Init the Annotation CNC Job color
  1509. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  1510. self.defaults['cncjob_annotation_fontcolor'])
  1511. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  1512. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  1513. # Init the Tool Film color
  1514. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  1515. self.defaults['tools_film_color'])
  1516. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  1517. "background-color:%s" % str(self.defaults['tools_film_color'])[:7])
  1518. # Init the Tool QRCode colors
  1519. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(
  1520. self.defaults['tools_qrcode_fill_color'])
  1521. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  1522. "background-color:%s" % str(self.defaults['tools_qrcode_fill_color'])[:7])
  1523. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(
  1524. self.defaults['tools_qrcode_back_color'])
  1525. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  1526. "background-color:%s" % str(self.defaults['tools_qrcode_back_color'])[:7])
  1527. # ### End of Data ####
  1528. # ##############################################
  1529. # ######### SETUP OBJECT COLLECTION ############
  1530. # ##############################################
  1531. self.collection = ObjectCollection(self)
  1532. self.ui.project_tab_layout.addWidget(self.collection.view)
  1533. # ### Adjust tabs width ## ##
  1534. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1535. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1536. self.collection.view.setMinimumWidth(290)
  1537. self.log.debug("Finished creating Object Collection.")
  1538. # ###############################################
  1539. # ############# SETUP Plot Area #################
  1540. # ###############################################
  1541. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  1542. if self.defaults["global_graphic_engine"] == '3D':
  1543. self.is_legacy = False
  1544. else:
  1545. self.is_legacy = True
  1546. # Matplotlib axis
  1547. self.axes = None
  1548. if show_splash:
  1549. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1550. "Canvas initialization started."),
  1551. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1552. color=QtGui.QColor("gray"))
  1553. start_plot_time = time.time() # debug
  1554. self.plotcanvas = None
  1555. self.app_cursor = None
  1556. self.hover_shapes = None
  1557. self.on_plotcanvas_setup()
  1558. end_plot_time = time.time()
  1559. self.used_time = end_plot_time - start_plot_time
  1560. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1561. if show_splash:
  1562. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1563. "Canvas initialization started.\n"
  1564. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1565. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1566. color=QtGui.QColor("gray"))
  1567. self.ui.splitter.setStretchFactor(1, 2)
  1568. # #################################################################
  1569. # ####################### SYS TRAY ################################
  1570. # #################################################################
  1571. if self.defaults["global_systray_icon"]:
  1572. self.parent_w = QtWidgets.QWidget()
  1573. if self.cmd_line_headless == 1:
  1574. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1575. headless=True,
  1576. parent=self.parent_w)
  1577. else:
  1578. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1579. parent=self.parent_w)
  1580. # #################################################################
  1581. # ####################### Worker SETUP ############################
  1582. # #################################################################
  1583. if self.defaults["global_worker_number"]:
  1584. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1585. else:
  1586. self.workers = WorkerStack(workers_number=2)
  1587. self.worker_task.connect(self.workers.add_task)
  1588. self.log.debug("Finished creating Workers crew.")
  1589. # #################################################################
  1590. # ######################## Activity Monitor #######################
  1591. # #################################################################
  1592. if self.defaults["global_activity_icon"] == "Ball green":
  1593. icon = 'share/active_2_static.png'
  1594. movie = "share/active_2.gif"
  1595. elif self.defaults["global_activity_icon"] == "Ball black":
  1596. icon = 'share/active_static.png'
  1597. movie = "share/active.gif"
  1598. elif self.defaults["global_activity_icon"] == "Arrow green":
  1599. icon = 'share/active_3_static.png'
  1600. movie = "share/active_3.gif"
  1601. elif self.defaults["global_activity_icon"] == "Eclipse green":
  1602. icon = 'share/active_4_static.png'
  1603. movie = "share/active_4.gif"
  1604. else:
  1605. icon = 'share/active_static.png'
  1606. movie = "share/active.gif"
  1607. self.activity_view = FlatCAMActivityView(icon=icon, movie=movie)
  1608. self.ui.infobar.addWidget(self.activity_view)
  1609. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  1610. # #################################################################
  1611. # ######################### Signal handling #######################
  1612. # #################################################################
  1613. # ########################### Custom signals #####################
  1614. # signal for displaying messages in status bar
  1615. self.inform.connect(self.info)
  1616. # signal to be called when the app is quiting
  1617. self.app_quit.connect(self.quit_application)
  1618. self.message.connect(self.message_dialog)
  1619. self.progress.connect(self.set_progress_bar)
  1620. # signals that are emitted when object state changes
  1621. self.object_created.connect(self.on_object_created)
  1622. self.object_changed.connect(self.on_object_changed)
  1623. self.object_plotted.connect(self.on_object_plotted)
  1624. self.plots_updated.connect(self.on_plots_updated)
  1625. # signals emitted when file state change
  1626. self.file_opened.connect(self.register_recent)
  1627. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1628. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1629. # ############# Standard signals ###################
  1630. # ### Menu
  1631. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1632. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1633. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1634. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1635. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  1636. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1637. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1638. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1639. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1640. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1641. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1642. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1643. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1644. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1645. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1646. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1647. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1648. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1649. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1650. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1651. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1652. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1653. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1654. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1655. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1656. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1657. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1658. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1659. self.ui.menufile_exit.triggered.connect(self.final_save)
  1660. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1661. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1662. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1663. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1664. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1665. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1666. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1667. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1668. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1669. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1670. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1671. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1672. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1673. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1674. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1675. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1676. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1677. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1678. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1679. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1680. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1681. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1682. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1683. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1684. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1685. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1686. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1687. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1688. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1689. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1690. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1691. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1692. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1693. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1694. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1695. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1696. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1697. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1698. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1699. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  1700. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1701. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  1702. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1703. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1704. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1705. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1706. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1707. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1708. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1709. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1710. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1711. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1712. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1713. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1714. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1715. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1716. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1717. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1718. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1719. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1720. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1721. # ToolBar signals
  1722. self.connect_toolbar_signals()
  1723. # Notebook and Plot Tab Area signals
  1724. # make the right click on the notebook tab and plot tab area tab raise a menu
  1725. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1726. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1727. self.on_tab_setup_context_menu()
  1728. # activate initial state
  1729. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1730. # Context Menu
  1731. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1732. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1733. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1734. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1735. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1736. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1737. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1738. self.ui.clearplot.triggered.connect(self.clear_plots)
  1739. self.ui.replot.triggered.connect(self.plot_all)
  1740. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1741. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1742. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1743. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1744. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1745. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1746. # Preferences Plot Area TAB
  1747. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1748. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1749. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1750. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1751. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1752. # ##############################
  1753. # ### GUI PREFERENCES SIGNALS ##
  1754. # ##############################
  1755. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  1756. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1757. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1758. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1759. )
  1760. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1761. lambda: self.on_toggle_units(no_pref=False))
  1762. # ###############################################################
  1763. # ################### GUI COLORS SIGNALS ########################
  1764. # ###############################################################
  1765. # Setting plot colors signals
  1766. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1767. self.on_pf_color_entry)
  1768. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1769. self.on_pf_color_button)
  1770. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1771. self.on_pf_color_spinner)
  1772. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1773. self.on_pf_color_slider)
  1774. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1775. self.on_pl_color_entry)
  1776. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1777. self.on_pl_color_button)
  1778. # Setting selection (left - right) colors signals
  1779. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1780. self.on_sf_color_entry)
  1781. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1782. self.on_sf_color_button)
  1783. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1784. self.on_sf_color_spinner)
  1785. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1786. self.on_sf_color_slider)
  1787. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1788. self.on_sl_color_entry)
  1789. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1790. self.on_sl_color_button)
  1791. # Setting selection (right - left) colors signals
  1792. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1793. self.on_alt_sf_color_entry)
  1794. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1795. self.on_alt_sf_color_button)
  1796. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1797. self.on_alt_sf_color_spinner)
  1798. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1799. self.on_alt_sf_color_slider)
  1800. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1801. self.on_alt_sl_color_entry)
  1802. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1803. self.on_alt_sl_color_button)
  1804. # Setting Editor Draw colors signals
  1805. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1806. self.on_draw_color_entry)
  1807. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1808. self.on_draw_color_button)
  1809. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1810. self.on_sel_draw_color_entry)
  1811. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1812. self.on_sel_draw_color_button)
  1813. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1814. self.on_proj_color_entry)
  1815. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1816. self.on_proj_color_button)
  1817. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1818. self.on_proj_color_dis_entry)
  1819. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1820. self.on_proj_color_dis_button)
  1821. # ########## workspace setting signals ###########
  1822. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1823. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1824. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1825. # #################################################
  1826. # ############ GUI SETTINGS SIGNALS ###############
  1827. # #################################################
  1828. self.ui.general_defaults_form.general_gui_set_group.theme_radio.activated_custom.connect(self.on_theme_change)
  1829. self.ui.general_defaults_form.general_gui_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1830. # ########## CNC Job related signals #############
  1831. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1832. self.on_cnc_custom_parameters)
  1833. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.editingFinished.connect(
  1834. self.on_annotation_fontcolor_entry)
  1835. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.clicked.connect(
  1836. self.on_annotation_fontcolor_button)
  1837. # ########## Tools related signals #############
  1838. # Film Tool
  1839. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1840. self.on_film_color_entry)
  1841. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1842. self.on_film_color_button)
  1843. # QRCode Tool
  1844. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  1845. self.on_qrcode_fill_color_entry)
  1846. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  1847. self.on_qrcode_fill_color_button)
  1848. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  1849. self.on_qrcode_back_color_entry)
  1850. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  1851. self.on_qrcode_back_color_button)
  1852. # portability changed signal
  1853. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1854. # Object list
  1855. self.collection.view.activated.connect(self.on_row_activated)
  1856. self.collection.item_selected.connect(self.on_row_selected)
  1857. self.object_status_changed.connect(self.on_collection_updated)
  1858. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1859. self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1860. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1861. # Export Excellon parameters.
  1862. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1863. self.on_update_exc_export
  1864. )
  1865. # call it once to make sure it is updated at startup
  1866. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1867. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1868. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1869. self.on_excellon_defaults_button)
  1870. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1871. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1872. self.on_excellon_options_button)
  1873. # when there are arguments at application startup this get launched
  1874. self.args_at_startup[list].connect(self.on_startup_args)
  1875. # ##############################################################
  1876. # ############### FILE ASSOCIATIONS SIGNALS ####################
  1877. # ##############################################################
  1878. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1879. lambda: self.restore_extensions(ext_type='excellon'))
  1880. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1881. lambda: self.restore_extensions(ext_type='gcode'))
  1882. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1883. lambda: self.restore_extensions(ext_type='gerber'))
  1884. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1885. lambda: self.delete_all_extensions(ext_type='excellon'))
  1886. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1887. lambda: self.delete_all_extensions(ext_type='gcode'))
  1888. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1889. lambda: self.delete_all_extensions(ext_type='gerber'))
  1890. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1891. lambda: self.add_extension(ext_type='excellon'))
  1892. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1893. lambda: self.add_extension(ext_type='gcode'))
  1894. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1895. lambda: self.add_extension(ext_type='gerber'))
  1896. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1897. lambda: self.del_extension(ext_type='excellon'))
  1898. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1899. lambda: self.del_extension(ext_type='gcode'))
  1900. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1901. lambda: self.del_extension(ext_type='gerber'))
  1902. # connect the 'Apply' buttons from the Preferences/File Associations
  1903. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1904. lambda: self.on_register_files(obj_type='excellon'))
  1905. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1906. lambda: self.on_register_files(obj_type='gcode'))
  1907. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1908. lambda: self.on_register_files(obj_type='gerber'))
  1909. # ##############################################################
  1910. # ###################### KEYWORDS SIGNALS ######################
  1911. # ##############################################################
  1912. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1913. lambda: self.restore_extensions(ext_type='keyword'))
  1914. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1915. lambda: self.delete_all_extensions(ext_type='keyword'))
  1916. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1917. lambda: self.add_extension(ext_type='keyword'))
  1918. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1919. lambda: self.del_extension(ext_type='keyword'))
  1920. # splash screen button signal
  1921. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1922. # connect the abort_all_tasks related slots to the related signals
  1923. self.proc_container.idle_flag.connect(self.app_is_idle)
  1924. # signal emitted when a tab is closed in the Plot Area
  1925. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  1926. # #####################################################################################
  1927. # ########### FINISHED CONNECTING SIGNALS #############################################
  1928. # #####################################################################################
  1929. self.log.debug("Finished connecting Signals.")
  1930. # #####################################################################################
  1931. # ########################## Other setups #############################################
  1932. # #####################################################################################
  1933. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  1934. # depending on from where those tools are called different actions can be done
  1935. self.call_source = 'app'
  1936. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1937. self.tool_tab_locked = False
  1938. # decide if to show or hide the Notebook side of the screen at startup
  1939. if self.defaults["global_project_at_startup"] is True:
  1940. self.ui.splitter.setSizes([1, 1])
  1941. else:
  1942. self.ui.splitter.setSizes([0, 1])
  1943. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1944. self.setup_obj_classes()
  1945. self.setup_recent_items()
  1946. self.setup_component_editor()
  1947. # this does not work in Legacy Mode
  1948. if self.is_legacy is True:
  1949. self.ui.general_defaults_form.general_gui_group.workspace_cb.setDisabled(True)
  1950. self.ui.general_defaults_form.general_gui_group.workspace_type_lbl.setDisabled(True)
  1951. self.ui.general_defaults_form.general_gui_group.wk_cb.setDisabled(True)
  1952. # #####################################################################################
  1953. # ######################### Auto-complete KEYWORDS ####################################
  1954. # #####################################################################################
  1955. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1956. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1957. 'delete', 'drillcncjob', 'export_gcode', 'export_svg', 'ext', 'exteriors', 'follow',
  1958. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1959. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1960. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1961. 'mirror', 'ncc',
  1962. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1963. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'origin',
  1964. 'paint', 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'quit_flatcam',
  1965. 'save', 'save_project',
  1966. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_sys',
  1967. 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1968. 'version', 'write_gcode'
  1969. ]
  1970. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'Marius', 'My Documents', 'Paste_1',
  1971. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1972. 'Toolchange_manual', 'Users', 'all', 'angle_x', 'angle_y', 'auto', 'axis',
  1973. 'axisoffset',
  1974. 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect', 'contour', 'default',
  1975. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dwell',
  1976. 'dwelltime', 'feedrate_z', 'grbl_11', 'grbl_laser', 'gridoffsety', 'gridx', 'gridy',
  1977. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1978. 'milled_dias', 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order',
  1979. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1980. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1981. 'spacing_columns',
  1982. 'spacing_rows', 'spindlespeed', 'toolchange_xy', 'tooldia', 'use_threads', 'value',
  1983. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1984. ]
  1985. self.tcl_keywords = [
  1986. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1987. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1988. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1989. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1990. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1991. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1992. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1993. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1994. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1995. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1996. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1997. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1998. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1999. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  2000. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  2001. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  2002. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  2003. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  2004. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  2005. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  2006. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  2007. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  2008. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  2009. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  2010. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  2011. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  2012. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  2013. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  2014. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  2015. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  2016. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  2017. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  2018. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  2019. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  2020. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  2021. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  2022. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  2023. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  2024. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  2025. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  2026. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  2027. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  2028. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  2029. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  2030. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  2031. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  2032. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  2033. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  2034. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  2035. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  2036. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  2037. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  2038. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  2039. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  2040. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  2041. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  2042. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  2043. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  2044. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  2045. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  2046. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  2047. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  2048. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  2049. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  2050. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  2051. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  2052. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  2053. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  2054. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  2055. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  2056. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  2057. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  2058. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  2059. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  2060. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  2061. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  2062. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  2063. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  2064. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  2065. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  2066. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  2067. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  2068. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  2069. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  2070. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  2071. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  2072. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  2073. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  2074. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  2075. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  2076. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  2077. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  2078. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  2079. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  2080. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  2081. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  2082. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  2083. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  2084. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  2085. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  2086. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  2087. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  2088. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  2089. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  2090. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  2091. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  2092. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  2093. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  2094. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  2095. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  2096. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  2097. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  2098. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  2099. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  2100. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  2101. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  2102. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  2103. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  2104. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  2105. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  2106. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  2107. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  2108. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  2109. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  2110. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  2111. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  2112. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  2113. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  2114. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  2115. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  2116. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  2117. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  2118. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  2119. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  2120. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  2121. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  2122. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  2123. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  2124. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  2125. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  2126. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  2127. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  2128. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  2129. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  2130. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  2131. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  2132. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  2133. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  2134. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  2135. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  2136. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  2137. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  2138. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  2139. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  2140. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  2141. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  2142. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  2143. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  2144. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  2145. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  2146. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  2147. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  2148. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  2149. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  2150. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  2151. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  2152. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  2153. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  2154. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  2155. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  2156. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  2157. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  2158. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  2159. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  2160. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  2161. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  2162. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  2163. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  2164. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  2165. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  2166. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  2167. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  2168. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  2169. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  2170. ]
  2171. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  2172. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2173. # ####################################################################################
  2174. # ####################### Shell SETUP ################################################
  2175. # ####################################################################################
  2176. # this will hold the TCL instance
  2177. self.tcl = None
  2178. self.init_tcl()
  2179. self.shell = FCShell(self, version=self.version)
  2180. self.shell._edit.set_model_data(self.myKeywords)
  2181. self.shell.setWindowIcon(self.ui.app_icon)
  2182. self.shell.setWindowTitle("FlatCAM Shell")
  2183. self.shell.resize(*self.defaults["global_shell_shape"])
  2184. self.shell.append_output("FlatCAM %s - " % self.version)
  2185. self.shell.append_output(_("Type >help< to get started\n\n"))
  2186. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  2187. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  2188. self.ui.shell_dock.setWidget(self.shell)
  2189. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  2190. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  2191. QtWidgets.QDockWidget.DockWidgetFloatable |
  2192. QtWidgets.QDockWidget.DockWidgetClosable)
  2193. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  2194. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  2195. if self.defaults["global_shell_at_startup"]:
  2196. self.ui.shell_dock.show()
  2197. else:
  2198. self.ui.shell_dock.hide()
  2199. # ##################################################################################
  2200. # ###################### Tools and Plugins #########################################
  2201. # ##################################################################################
  2202. self.dblsidedtool = None
  2203. self.distance_tool = None
  2204. self.distance_min_tool = None
  2205. self.panelize_tool = None
  2206. self.film_tool = None
  2207. self.paste_tool = None
  2208. self.calculator_tool = None
  2209. self.rules_tool = None
  2210. self.sub_tool = None
  2211. self.move_tool = None
  2212. self.cutout_tool = None
  2213. self.ncclear_tool = None
  2214. self.optimal_tool = None
  2215. self.paint_tool = None
  2216. self.transform_tool = None
  2217. self.properties_tool = None
  2218. self.pdf_tool = None
  2219. self.image_tool = None
  2220. self.pcb_wizard_tool = None
  2221. self.cal_exc_tool = None
  2222. self.qrcode_tool = None
  2223. self.copperfill_tool = None
  2224. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  2225. self.install_tools()
  2226. # ##################################################################################
  2227. # ########################### BookMarks Manager ####################################
  2228. # ##################################################################################
  2229. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  2230. self.install_bookmarks()
  2231. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  2232. # ### System Font Parsing ###
  2233. # self.f_parse = ParseFont(self)
  2234. # self.parse_system_fonts()
  2235. # #####################################################################################
  2236. # ######################## Check for updates ##########################################
  2237. # #####################################################################################
  2238. # Separate thread (Not worker)
  2239. # Check for updates on startup but only if the user consent and the app is not in Beta version
  2240. if (self.beta is False or self.beta is None) and \
  2241. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  2242. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  2243. self.thr2 = QtCore.QThread()
  2244. self.worker_task.emit({'fcn': self.version_check,
  2245. 'params': []})
  2246. self.thr2.start(QtCore.QThread.LowPriority)
  2247. # #####################################################################################
  2248. # ######################### Register files with FlatCAM; #############################
  2249. # ######################### It works only for Windows for now ########################
  2250. # #####################################################################################
  2251. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  2252. self.on_register_files()
  2253. # #####################################################################################
  2254. # ###################### Variables for global usage ###################################
  2255. # #####################################################################################
  2256. # coordinates for relative position display
  2257. self.rel_point1 = (0, 0)
  2258. self.rel_point2 = (0, 0)
  2259. # variable to store coordinates
  2260. self.pos = (0, 0)
  2261. self.pos_jump = (0, 0)
  2262. # variable to store mouse coordinates
  2263. self.mouse = [0, 0]
  2264. # decide if we have a double click or single click
  2265. self.doubleclick = False
  2266. # variable to store if a command is active (then the var is not None) and which one it is
  2267. self.command_active = None
  2268. # variable to store the status of moving selection action
  2269. # None value means that it's not an selection action
  2270. # True value = a selection from left to right
  2271. # False value = a selection from right to left
  2272. self.selection_type = None
  2273. # List to store the objects that are currently loaded in FlatCAM
  2274. # This list is updated on each object creation or object delete
  2275. self.all_objects_list = list()
  2276. # List to store the objects that are selected
  2277. self.sel_objects_list = list()
  2278. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2279. self.key_modifiers = None
  2280. # Variable to hold the status of the axis
  2281. self.toggle_axis = True
  2282. # Variable to hold the status of the grid lines
  2283. self.toggle_grid_lines = True
  2284. # Variable to store the status of the fullscreen event
  2285. self.toggle_fscreen = False
  2286. # Variable to store the status of the code editor
  2287. self.toggle_codeeditor = False
  2288. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2289. self.click_noproject = False
  2290. self.cursor = None
  2291. # Variable to store the GCODE that was edited
  2292. self.gcode_edited = ""
  2293. self.text_editor_tab = None
  2294. # reference for the self.ui.code_editor
  2295. self.reference_code_editor = None
  2296. self.script_code = ''
  2297. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2298. self.preferences_changed_flag = False
  2299. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2300. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2301. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'pho',
  2302. 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top', 'tsm']
  2303. self.exc_list = ['drd', 'drl', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2304. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2305. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ncp', 'out', 'plt', 'ply', 'rol', 'sbp',
  2306. 'tap', 'xpi']
  2307. self.svg_list = ['svg']
  2308. self.dxf_list = ['dxf']
  2309. self.pdf_list = ['pdf']
  2310. self.prj_list = ['flatprj']
  2311. self.conf_list = ['flatconfig']
  2312. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2313. # flag for polygons not cleared
  2314. self.poly_not_cleared = False
  2315. # VisPy visuals
  2316. self.isHovering = False
  2317. self.notHovering = True
  2318. # Window geometry
  2319. self.x_pos = None
  2320. self.y_pos = None
  2321. self.width = None
  2322. self.height = None
  2323. # Event signals disconnect id holders
  2324. self.mp = None
  2325. self.mm = None
  2326. self.mr = None
  2327. self.mp_zc = None
  2328. # when True, the app has to return from any thread
  2329. self.abort_flag = False
  2330. # set the value used in the Windows Title
  2331. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  2332. # this holds a widget that is installed in the Plot Area when View Source option is used
  2333. self.source_editor_tab = None
  2334. # ###############################################################################
  2335. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  2336. # ############# It's done only once after install ###############
  2337. # ###############################################################################
  2338. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  2339. fac_def_from_file = factory_file.read()
  2340. factory_defaults = json.loads(fac_def_from_file)
  2341. # if the file contain an empty dictionary then save the factory defaults into the file
  2342. if not factory_defaults:
  2343. self.save_factory_defaults(silent_message=False)
  2344. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  2345. initial_lay = 'compact'
  2346. self.on_layout(lay=initial_lay)
  2347. # Set the combobox in Preferences to the current layout
  2348. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  2349. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  2350. factory_file.close()
  2351. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  2352. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  2353. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  2354. # after the first run, this object should be False
  2355. self.defaults["first_run"] = False
  2356. # ###############################################################################
  2357. # ################# ADDING FlatCAM EDITORS section ##############################
  2358. # ###############################################################################
  2359. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2360. # at the first launch of the App , the editors will not be functional.
  2361. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2362. self.exc_editor = FlatCAMExcEditor(self)
  2363. self.grb_editor = FlatCAMGrbEditor(self)
  2364. self.log.debug("Finished adding FlatCAM Editor's.")
  2365. self.set_ui_title(name=_("New Project - Not saved"))
  2366. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2367. current_platform = platform.architecture()[0]
  2368. if current_platform != '64bit':
  2369. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2370. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2371. # ###############################################################################
  2372. # ####################### Finished the CONSTRUCTOR ##############################
  2373. # ###############################################################################
  2374. App.log.debug("END of constructor. Releasing control.")
  2375. # #####################################################################################
  2376. # ########################## SHOW GUI #################################################
  2377. # #####################################################################################
  2378. # if the app is not started as headless, show it
  2379. if self.cmd_line_headless != 1:
  2380. if show_splash:
  2381. # finish the splash
  2382. self.splash.finish(self.ui)
  2383. settings = QSettings("Open Source", "FlatCAM")
  2384. if settings.contains("maximized_gui"):
  2385. maximized_ui = settings.value('maximized_gui', type=bool)
  2386. if maximized_ui is True:
  2387. self.ui.showMaximized()
  2388. else:
  2389. self.ui.show()
  2390. else:
  2391. self.ui.show()
  2392. if self.defaults["global_systray_icon"]:
  2393. self.trayIcon.show()
  2394. else:
  2395. log.warning("******************* RUNNING HEADLESS *******************")
  2396. # #####################################################################################
  2397. # ########################## START-UP ARGUMENTS #######################################
  2398. # #####################################################################################
  2399. # test if the program was started with a script as parameter
  2400. if self.cmd_line_shellvar:
  2401. try:
  2402. cnt = 0
  2403. command_tcl = 0
  2404. for i in self.cmd_line_shellvar.split(','):
  2405. if i is not None:
  2406. try:
  2407. command_tcl = eval(i)
  2408. except:
  2409. command_tcl = i
  2410. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  2411. cnt += 1
  2412. # if there are Windows paths then replace the path separator with a Unix like one
  2413. if sys.platform == 'win32':
  2414. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2415. self.shell._sysShell.exec_command(command_tcl_formatted, no_echo=True)
  2416. except Exception as ext:
  2417. print("ERROR: ", ext)
  2418. sys.exit(2)
  2419. if self.cmd_line_shellfile:
  2420. try:
  2421. if self.ui.shell_dock.isHidden():
  2422. self.ui.shell_dock.show()
  2423. with open(self.cmd_line_shellfile, "r") as myfile:
  2424. if show_splash:
  2425. self.splash.showMessage('%s: %ssec\n%s' % (
  2426. _("Canvas initialization started.\n"
  2427. "Canvas initialization finished in"), '%.2f' % self.used_time,
  2428. _("Executing Tcl Script ...")),
  2429. alignment=Qt.AlignBottom | Qt.AlignLeft,
  2430. color=QtGui.QColor("gray"))
  2431. cmd_line_shellfile_text = myfile.read()
  2432. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2433. except Exception as ext:
  2434. print("ERROR: ", ext)
  2435. sys.exit(2)
  2436. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2437. # the path/file_name must be enclosed in quotes if it contain spaces
  2438. if App.args:
  2439. self.args_at_startup.emit(App.args)
  2440. @staticmethod
  2441. def copy_and_overwrite(from_path, to_path):
  2442. """
  2443. From here:
  2444. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2445. :param from_path: source path
  2446. :param to_path: destination path
  2447. :return: None
  2448. """
  2449. if os.path.exists(to_path):
  2450. shutil.rmtree(to_path)
  2451. try:
  2452. shutil.copytree(from_path, to_path)
  2453. except FileNotFoundError:
  2454. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2455. shutil.copytree(from_new_path, to_path)
  2456. def on_startup_args(self, args, silent=False):
  2457. """
  2458. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2459. :param args: a list containing the application args at startup
  2460. :return: None
  2461. """
  2462. if args is not None:
  2463. args_to_process = args
  2464. else:
  2465. args_to_process = App.args
  2466. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2467. for argument in args_to_process:
  2468. if '.FlatPrj'.lower() in argument.lower():
  2469. try:
  2470. project_name = str(argument)
  2471. if project_name == "":
  2472. if silent is False:
  2473. self.inform.emit(_("Open cancelled."))
  2474. else:
  2475. # self.open_project(project_name)
  2476. run_from_arg = True
  2477. # self.worker_task.emit({'fcn': self.open_project,
  2478. # 'params': [project_name, run_from_arg]})
  2479. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2480. except Exception as e:
  2481. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2482. elif '.FlatConfig'.lower() in argument.lower():
  2483. try:
  2484. file_name = str(argument)
  2485. if file_name == "":
  2486. if silent is False:
  2487. self.inform.emit(_("Open Config file failed."))
  2488. else:
  2489. run_from_arg = True
  2490. # self.worker_task.emit({'fcn': self.open_config_file,
  2491. # 'params': [file_name, run_from_arg]})
  2492. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2493. except Exception as e:
  2494. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2495. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  2496. try:
  2497. file_name = str(argument)
  2498. if file_name == "":
  2499. if silent is False:
  2500. self.inform.emit(_("Open Script file failed."))
  2501. else:
  2502. if silent is False:
  2503. self.on_fileopenscript(name=file_name)
  2504. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  2505. self.on_filerunscript(name=file_name)
  2506. except Exception as e:
  2507. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2508. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  2509. log.debug("App.on_startup_args() --> Quit event.")
  2510. sys.exit()
  2511. elif 'save'.lower() in argument.lower():
  2512. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2513. self.save_defaults()
  2514. else:
  2515. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2516. proc_arg = argument.lower()
  2517. for ext in exc_list:
  2518. proc_ext = ext.replace(' ', '')
  2519. proc_ext = '.%s' % proc_ext
  2520. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2521. file_name = str(argument)
  2522. if file_name == "":
  2523. if silent is False:
  2524. self.inform.emit(_("Open Excellon file failed."))
  2525. else:
  2526. self.on_fileopenexcellon(name=file_name)
  2527. return
  2528. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2529. for ext in gco_list:
  2530. proc_ext = ext.replace(' ', '')
  2531. proc_ext = '.%s' % proc_ext
  2532. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2533. file_name = str(argument)
  2534. if file_name == "":
  2535. if silent is False:
  2536. self.inform.emit(_("Open GCode file failed."))
  2537. else:
  2538. self.on_fileopengcode(name=file_name)
  2539. return
  2540. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2541. for ext in grb_list:
  2542. proc_ext = ext.replace(' ', '')
  2543. proc_ext = '.%s' % proc_ext
  2544. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2545. file_name = str(argument)
  2546. if file_name == "":
  2547. if silent is False:
  2548. self.inform.emit(_("Open Gerber file failed."))
  2549. else:
  2550. self.on_fileopengerber(name=file_name)
  2551. return
  2552. # if it reached here without already returning then the app was registered with a file that it does not
  2553. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  2554. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  2555. # for arg in args_to_process:
  2556. # if 'FlatCAM.exe' in arg:
  2557. # continue
  2558. # else:
  2559. # sys.exit(2)
  2560. def set_ui_title(self, name):
  2561. """
  2562. Sets the title of the main window.
  2563. :param name: String that store the project path and project name
  2564. :return: None
  2565. """
  2566. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  2567. (self.version,
  2568. ('BETA' if self.beta else ''),
  2569. platform.architecture()[0],
  2570. self.engine,
  2571. name)
  2572. )
  2573. def on_theme_change(self, val):
  2574. settings = QSettings("Open Source", "FlatCAM")
  2575. settings.setValue('theme', val)
  2576. # This will write the setting to the platform specific storage.
  2577. del settings
  2578. self.on_app_restart()
  2579. def on_app_restart(self):
  2580. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  2581. # be left in the SySTray
  2582. try:
  2583. self.trayIcon.hide()
  2584. except Exception as e:
  2585. pass
  2586. fcTranslate.restart_program(app=self)
  2587. def defaults_read_form(self):
  2588. """
  2589. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2590. :return: None
  2591. """
  2592. for option in self.defaults_form_fields:
  2593. try:
  2594. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2595. except Exception as e:
  2596. log.debug("App.defaults_read_form() --> %s" % str(e))
  2597. def defaults_write_form(self, factor=None, fl_units=None):
  2598. """
  2599. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2600. self.defaults dictionary.
  2601. :param factor: will apply a factor to the values that written in the GUI elements
  2602. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2603. :return: None
  2604. """
  2605. for option in self.defaults:
  2606. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2607. # try:
  2608. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2609. # except KeyError:
  2610. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2611. # # TODO: Rethink this?
  2612. # pass
  2613. def defaults_write_form_field(self, field, factor=None, units=None):
  2614. """
  2615. Basically it is the worker in the self.defaults_write_form()
  2616. :param field: the GUI element in Preferences GUI to be updated
  2617. :param factor: factor to be applied to the field parameter
  2618. :param units: current FLatCAM measuring units
  2619. :return: None, it updates GUI elements
  2620. """
  2621. try:
  2622. if factor is None:
  2623. if units is None:
  2624. self.defaults_form_fields[field].set_value(self.defaults[field])
  2625. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2626. self.defaults_form_fields[field].set_value(self.defaults[field])
  2627. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2628. self.defaults_form_fields[field].set_value(self.defaults[field])
  2629. else:
  2630. if units is None:
  2631. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2632. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2633. self.defaults_form_fields[field].set_value((self.defaults[field] * factor))
  2634. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2635. self.defaults_form_fields[field].set_value((self.defaults[field] * factor))
  2636. except KeyError:
  2637. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2638. # TODO: Rethink this?
  2639. pass
  2640. except AttributeError:
  2641. log.debug(field)
  2642. def clear_pool(self):
  2643. """
  2644. Clear the multiprocessing pool and calls garbage collector.
  2645. :return: None
  2646. """
  2647. self.pool.close()
  2648. self.pool = Pool()
  2649. self.pool_recreated.emit(self.pool)
  2650. gc.collect()
  2651. def install_tools(self):
  2652. """
  2653. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2654. Instantiation of the Tools classes.
  2655. The order that the tools are installed is important as they can depend on each other install position.
  2656. :return: None
  2657. """
  2658. self.dblsidedtool = DblSidedTool(self)
  2659. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2660. self.cal_exc_tool = ToolCalibrateExcellon(self)
  2661. self.cal_exc_tool.install(icon=QtGui.QIcon('share/drill16.png'), pos=self.ui.menutool,
  2662. before=self.dblsidedtool.menuAction,
  2663. separator=False)
  2664. self.distance_tool = Distance(self)
  2665. self.distance_tool.install(icon=QtGui.QIcon('share/distance16.png'), pos=self.ui.menuedit,
  2666. before=self.ui.menueditorigin,
  2667. separator=False)
  2668. self.distance_min_tool = DistanceMin(self)
  2669. self.distance_min_tool.install(icon=QtGui.QIcon('share/distance_min16.png'), pos=self.ui.menuedit,
  2670. before=self.ui.menueditorigin,
  2671. separator=True)
  2672. self.panelize_tool = Panelize(self)
  2673. self.panelize_tool.install(icon=QtGui.QIcon('share/panelize16.png'))
  2674. self.film_tool = Film(self)
  2675. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2676. self.paste_tool = SolderPaste(self)
  2677. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2678. self.calculator_tool = ToolCalculator(self)
  2679. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator16.png'), separator=True)
  2680. self.sub_tool = ToolSub(self)
  2681. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2682. self.rules_tool = RulesCheck(self)
  2683. self.rules_tool.install(icon=QtGui.QIcon('share/rules32.png'), pos=self.ui.menutool, separator=False)
  2684. self.optimal_tool = ToolOptimal(self)
  2685. self.optimal_tool.install(icon=QtGui.QIcon('share/open_excellon32.png'), pos=self.ui.menutool, separator=True)
  2686. self.move_tool = ToolMove(self)
  2687. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2688. before=self.ui.menueditorigin, separator=True)
  2689. self.cutout_tool = CutOut(self)
  2690. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2691. before=self.sub_tool.menuAction)
  2692. self.ncclear_tool = NonCopperClear(self)
  2693. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2694. before=self.sub_tool.menuAction, separator=True)
  2695. self.paint_tool = ToolPaint(self)
  2696. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2697. before=self.sub_tool.menuAction, separator=True)
  2698. self.copperfill_tool = ToolCopperFill(self)
  2699. self.copperfill_tool.install(icon=QtGui.QIcon('share/copperfill32.png'), pos=self.ui.menutool)
  2700. self.qrcode_tool = QRCode(self)
  2701. self.qrcode_tool.install(icon=QtGui.QIcon('share/qrcode32.png'), pos=self.ui.menutool)
  2702. self.transform_tool = ToolTransform(self)
  2703. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2704. self.properties_tool = Properties(self)
  2705. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2706. self.pdf_tool = ToolPDF(self)
  2707. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2708. separator=True)
  2709. self.image_tool = ToolImage(self)
  2710. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2711. separator=True)
  2712. self.pcb_wizard_tool = PcbWizard(self)
  2713. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2714. self.log.debug("Tools are installed.")
  2715. def remove_tools(self):
  2716. """
  2717. Will remove all the actions in the Tool menu.
  2718. :return: None
  2719. """
  2720. for act in self.ui.menutool.actions():
  2721. self.ui.menutool.removeAction(act)
  2722. def init_tools(self):
  2723. """
  2724. Initialize the Tool tab in the notebook side of the central widget.
  2725. Remove the actions in the Tools menu.
  2726. Instantiate again the FlatCAM tools (plugins).
  2727. All this is required when changing the layout: standard, compact etc.
  2728. :return: None
  2729. """
  2730. log.debug("init_tools()")
  2731. # delete the data currently in the Tools Tab and the Tab itself
  2732. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2733. if widget is not None:
  2734. widget.deleteLater()
  2735. self.ui.notebook.removeTab(2)
  2736. # rebuild the Tools Tab
  2737. self.ui.tool_tab = QtWidgets.QWidget()
  2738. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2739. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2740. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2741. self.ui.tool_scroll_area = VerticalScrollArea()
  2742. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2743. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2744. # first remove all of them
  2745. self.remove_tools()
  2746. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2747. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2748. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2749. # third install all of them
  2750. self.install_tools()
  2751. self.log.debug("Tools are initialized.")
  2752. # def parse_system_fonts(self):
  2753. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2754. # 'params': []})
  2755. def connect_toolbar_signals(self):
  2756. """
  2757. Reconnect the signals to the actions in the toolbar.
  2758. This has to be done each time after the FlatCAM tools are removed/installed.
  2759. :return: None
  2760. """
  2761. # Toolbar
  2762. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2763. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2764. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2765. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2766. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2767. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2768. self.ui.replot_btn.triggered.connect(self.plot_all)
  2769. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2770. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2771. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2772. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2773. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2774. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2775. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2776. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2777. self.ui.copy_btn.triggered.connect(self.on_copy_object)
  2778. self.ui.delete_btn.triggered.connect(self.on_delete)
  2779. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  2780. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  2781. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  2782. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  2783. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2784. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2785. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2786. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2787. # Tools Toolbar Signals
  2788. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2789. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2790. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2791. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2792. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2793. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2794. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2795. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2796. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  2797. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  2798. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2799. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2800. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  2801. self.ui.copperfill_btn.triggered.connect(lambda: self.copperfill_tool.run(toggle=True))
  2802. def object2editor(self):
  2803. """
  2804. Send the current Geometry or Excellon object (if any) into the it's editor.
  2805. :return: None
  2806. """
  2807. self.report_usage("object2editor()")
  2808. # disable the objects menu as it may interfere with the Editors
  2809. self.ui.menuobjects.setDisabled(True)
  2810. edited_object = self.collection.get_active()
  2811. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2812. isinstance(edited_object, FlatCAMExcellon):
  2813. pass
  2814. else:
  2815. self.inform.emit('[WARNING_NOTCL] %s' %
  2816. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2817. return
  2818. if isinstance(edited_object, FlatCAMGeometry):
  2819. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2820. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2821. # we set the notebook to hidden
  2822. self.ui.splitter.setSizes([0, 1])
  2823. if edited_object.multigeo is True:
  2824. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  2825. if len(edited_tools) > 1:
  2826. self.inform.emit('[WARNING_NOTCL] %s' %
  2827. _("Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  2828. "is not possible.\n"
  2829. "Edit only one geometry at a time."))
  2830. # determine the tool dia of the selected tool
  2831. selected_tooldia = float(edited_object.ui.geo_tools_table.item((edited_tools[0] - 1), 1).text())
  2832. # now find the key in the edited_object.tools that has this tooldia
  2833. multi_tool = 1
  2834. for tool in edited_object.tools:
  2835. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2836. multi_tool = tool
  2837. break
  2838. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2839. else:
  2840. self.geo_editor.edit_fcgeometry(edited_object)
  2841. # set call source to the Editor we go into
  2842. self.call_source = 'geo_editor'
  2843. elif isinstance(edited_object, FlatCAMExcellon):
  2844. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2845. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2846. if self.ui.splitter.sizes()[0] == 0:
  2847. self.ui.splitter.setSizes([1, 1])
  2848. self.exc_editor.edit_fcexcellon(edited_object)
  2849. # set call source to the Editor we go into
  2850. self.call_source = 'exc_editor'
  2851. elif isinstance(edited_object, FlatCAMGerber):
  2852. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2853. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2854. if self.ui.splitter.sizes()[0] == 0:
  2855. self.ui.splitter.setSizes([1, 1])
  2856. self.grb_editor.edit_fcgerber(edited_object)
  2857. # set call source to the Editor we go into
  2858. self.call_source = 'grb_editor'
  2859. # make sure that we can't select another object while in Editor Mode:
  2860. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2861. self.ui.project_frame.setDisabled(True)
  2862. # delete any selection shape that might be active as they are not relevant in Editor
  2863. self.delete_selection_shape()
  2864. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2865. self.ui.plot_tab_area.protectTab(0)
  2866. self.inform.emit('[WARNING_NOTCL] %s' %
  2867. _("Editor is activated ..."))
  2868. self.should_we_save = True
  2869. def editor2object(self, cleanup=None):
  2870. """
  2871. Transfers the Geometry or Excellon from it's editor to the current object.
  2872. :return: None
  2873. """
  2874. self.report_usage("editor2object()")
  2875. # re-enable the objects menu that was disabled on entry in Editor mode
  2876. self.ui.menuobjects.setDisabled(False)
  2877. # do not update a geometry or excellon object unless it comes out of an editor
  2878. if self.call_source != 'app':
  2879. edited_obj = self.collection.get_active()
  2880. if cleanup is None:
  2881. msgbox = QtWidgets.QMessageBox()
  2882. msgbox.setText(_("Do you want to save the edited object?"))
  2883. msgbox.setWindowTitle(_("Close Editor"))
  2884. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2885. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2886. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2887. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2888. msgbox.setDefaultButton(bt_yes)
  2889. msgbox.exec_()
  2890. response = msgbox.clickedButton()
  2891. if response == bt_yes:
  2892. # clean the Tools Tab
  2893. self.ui.tool_scroll_area.takeWidget()
  2894. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2895. self.ui.notebook.setTabText(2, "Tool")
  2896. if isinstance(edited_obj, FlatCAMGeometry):
  2897. obj_type = "Geometry"
  2898. if cleanup is None:
  2899. self.geo_editor.update_fcgeometry(edited_obj)
  2900. self.geo_editor.update_options(edited_obj)
  2901. self.geo_editor.deactivate()
  2902. # update the geo object options so it is including the bounding box values
  2903. try:
  2904. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2905. edited_obj.options['xmin'] = xmin
  2906. edited_obj.options['ymin'] = ymin
  2907. edited_obj.options['xmax'] = xmax
  2908. edited_obj.options['ymax'] = ymax
  2909. except AttributeError as e:
  2910. self.inform.emit('[WARNING] %s' %
  2911. _("Object empty after edit."))
  2912. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2913. elif isinstance(edited_obj, FlatCAMGerber):
  2914. obj_type = "Gerber"
  2915. if cleanup is None:
  2916. self.grb_editor.update_fcgerber()
  2917. self.grb_editor.update_options(edited_obj)
  2918. self.grb_editor.deactivate_grb_editor()
  2919. # delete the old object (the source object) if it was an empty one
  2920. try:
  2921. if len(edited_obj.solid_geometry) == 0:
  2922. old_name = edited_obj.options['name']
  2923. self.collection.set_active(old_name)
  2924. self.collection.delete_active()
  2925. except TypeError:
  2926. # if the solid_geometry is a single Polygon the len() will not work
  2927. # in any case, falling here means that we have something in the solid_geometry, even if only
  2928. # a single Polygon, therefore we pass this
  2929. pass
  2930. # restore GUI to the Selected TAB
  2931. # Remove anything else in the GUI
  2932. self.ui.selected_scroll_area.takeWidget()
  2933. # Switch notebook to Selected page
  2934. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2935. elif isinstance(edited_obj, FlatCAMExcellon):
  2936. obj_type = "Excellon"
  2937. if cleanup is None:
  2938. self.exc_editor.update_fcexcellon(edited_obj)
  2939. self.exc_editor.update_options(edited_obj)
  2940. self.exc_editor.deactivate()
  2941. # delete the old object (the source object) if it was an empty one
  2942. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  2943. old_name = edited_obj.options['name']
  2944. self.collection.set_active(old_name)
  2945. self.collection.delete_active()
  2946. # restore GUI to the Selected TAB
  2947. # Remove anything else in the GUI
  2948. self.ui.tool_scroll_area.takeWidget()
  2949. # Switch notebook to Selected page
  2950. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2951. else:
  2952. self.inform.emit('[WARNING_NOTCL] %s' %
  2953. _("Select a Gerber, Geometry or Excellon Object to update."))
  2954. return
  2955. self.inform.emit('[selected] %s %s' %
  2956. (obj_type, _("is updated, returning to App...")))
  2957. elif response == bt_no:
  2958. # clean the Tools Tab
  2959. self.ui.tool_scroll_area.takeWidget()
  2960. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2961. self.ui.notebook.setTabText(2, "Tool")
  2962. if isinstance(edited_obj, FlatCAMGeometry):
  2963. self.geo_editor.deactivate()
  2964. elif isinstance(edited_obj, FlatCAMGerber):
  2965. self.grb_editor.deactivate_grb_editor()
  2966. elif isinstance(edited_obj, FlatCAMExcellon):
  2967. self.exc_editor.deactivate()
  2968. # set focus on the project tab
  2969. else:
  2970. self.inform.emit('[WARNING_NOTCL] %s' %
  2971. _("Select a Gerber, Geometry or Excellon Object to update."))
  2972. return
  2973. edited_obj.set_ui(edited_obj.ui_type())
  2974. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2975. elif response == bt_cancel:
  2976. return
  2977. else:
  2978. if isinstance(edited_obj, FlatCAMGeometry):
  2979. self.geo_editor.deactivate()
  2980. elif isinstance(edited_obj, FlatCAMGerber):
  2981. self.grb_editor.deactivate_grb_editor()
  2982. elif isinstance(edited_obj, FlatCAMExcellon):
  2983. self.exc_editor.deactivate()
  2984. else:
  2985. self.inform.emit('[WARNING_NOTCL] %s' %
  2986. _("Select a Gerber, Geometry or Excellon Object to update."))
  2987. return
  2988. # if notebook is hidden we show it
  2989. if self.ui.splitter.sizes()[0] == 0:
  2990. self.ui.splitter.setSizes([1, 1])
  2991. # restore the call_source to app
  2992. self.call_source = 'app'
  2993. edited_obj.plot()
  2994. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2995. self.ui.plot_tab_area.protectTab(0)
  2996. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2997. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2998. self.ui.project_frame.setDisabled(False)
  2999. def get_last_folder(self):
  3000. """
  3001. Get the folder path from where the last file was opened.
  3002. :return: String, last opened folder path
  3003. """
  3004. return self.defaults["global_last_folder"]
  3005. def get_last_save_folder(self):
  3006. """
  3007. Get the folder path from where the last file was saved.
  3008. :return: String, last saved folder path
  3009. """
  3010. loc = self.defaults["global_last_save_folder"]
  3011. if loc is None:
  3012. loc = self.defaults["global_last_folder"]
  3013. if loc is None:
  3014. loc = os.path.dirname(__file__)
  3015. return loc
  3016. def report_usage(self, resource):
  3017. """
  3018. Increments usage counter for the given resource
  3019. in self.defaults['global_stats'].
  3020. :param resource: Name of the resource.
  3021. :return: None
  3022. """
  3023. if resource in self.defaults['global_stats']:
  3024. self.defaults['global_stats'][resource] += 1
  3025. else:
  3026. self.defaults['global_stats'][resource] = 1
  3027. def init_tcl(self):
  3028. """
  3029. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  3030. :return: None
  3031. """
  3032. if hasattr(self, 'tcl') and self.tcl is not None:
  3033. # self.tcl = None
  3034. # TODO we need to clean non default variables and procedures here
  3035. # new object cannot be used here as it will not remember values created for next passes,
  3036. # because tcl was execudted in old instance of TCL
  3037. pass
  3038. else:
  3039. self.tcl = tk.Tcl()
  3040. self.setup_shell()
  3041. self.log.debug("TCL Shell has been initialized.")
  3042. # TODO: This shouldn't be here.
  3043. class TclErrorException(Exception):
  3044. """
  3045. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  3046. """
  3047. pass
  3048. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  3049. """
  3050. Shows a message on the FlatCAM Shell
  3051. :param msg: Message to display.
  3052. :param show: Opens the shell.
  3053. :param error: Shows the message as an error.
  3054. :param warning: Shows the message as an warning.
  3055. :param success: Shows the message as an success.
  3056. :param selected: Indicate that something was selected on canvas
  3057. :return: None
  3058. """
  3059. if show:
  3060. self.ui.shell_dock.show()
  3061. try:
  3062. if error:
  3063. self.shell.append_error(msg + "\n")
  3064. elif warning:
  3065. self.shell.append_warning(msg + "\n")
  3066. elif success:
  3067. self.shell.append_success(msg + "\n")
  3068. elif selected:
  3069. self.shell.append_selected(msg + "\n")
  3070. else:
  3071. self.shell.append_output(msg + "\n")
  3072. except AttributeError:
  3073. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  3074. def raise_tcl_unknown_error(self, unknownException):
  3075. """
  3076. Raise exception if is different type than TclErrorException
  3077. this is here mainly to show unknown errors inside TCL shell console.
  3078. :param unknownException:
  3079. :return:
  3080. """
  3081. if not isinstance(unknownException, self.TclErrorException):
  3082. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  3083. else:
  3084. raise unknownException
  3085. def display_tcl_error(self, error, error_info=None):
  3086. """
  3087. Escape bracket [ with '\' otherwise there is error
  3088. "ERROR: missing close-bracket" instead of real error
  3089. :param error: it may be text or exception
  3090. :param error_info: Some informations about the error
  3091. :return: None
  3092. """
  3093. if isinstance(error, Exception):
  3094. exc_type, exc_value, exc_traceback = error_info
  3095. if not isinstance(error, self.TclErrorException):
  3096. show_trace = 1
  3097. else:
  3098. show_trace = int(self.defaults['global_verbose_error_level'])
  3099. if show_trace > 0:
  3100. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  3101. trc_formated = []
  3102. for a in reversed(trc):
  3103. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  3104. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  3105. else:
  3106. text = "%s" % error
  3107. else:
  3108. text = error
  3109. text = text.replace('[', '\\[').replace('"', '\\"')
  3110. self.tcl.eval('return -code error "%s"' % text)
  3111. def raise_tcl_error(self, text):
  3112. """
  3113. This method pass exception from python into TCL as error, so we get stacktrace and reason
  3114. :param text: text of error
  3115. :return: raise exception
  3116. """
  3117. self.display_tcl_error(text)
  3118. raise self.TclErrorException(text)
  3119. def exec_command(self, text, no_echo=False):
  3120. """
  3121. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  3122. Also handles execution in separated threads
  3123. :param text: FlatCAM TclCommand with parameters
  3124. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  3125. will create crashes of the _Expandable_Edit widget
  3126. :return: output if there was any
  3127. """
  3128. self.report_usage('exec_command')
  3129. result = self.exec_command_test(text, False, no_echo=no_echo)
  3130. # MS: added this method call so the geometry is updated once the TCL command is executed
  3131. # if no_plot is None:
  3132. # self.plot_all()
  3133. return result
  3134. def exec_command_test(self, text, reraise=True, no_echo=False):
  3135. """
  3136. Same as exec_command(...) with additional control over exceptions.
  3137. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  3138. :param text: Input command
  3139. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  3140. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  3141. will create crashes of the _Expandable_Edit widget
  3142. :return: Output from the command
  3143. """
  3144. tcl_command_string = str(text)
  3145. try:
  3146. if no_echo is False:
  3147. self.shell.open_proccessing() # Disables input box.
  3148. result = self.tcl.eval(str(tcl_command_string))
  3149. if result != 'None' and no_echo is False:
  3150. self.shell.append_output(result + '\n')
  3151. except tk.TclError as e:
  3152. # This will display more precise answer if something in TCL shell fails
  3153. result = self.tcl.eval("set errorInfo")
  3154. self.log.error("Exec command Exception: %s" % (result + '\n'))
  3155. if no_echo is False:
  3156. self.shell.append_error('ERROR: ' + result + '\n')
  3157. # Show error in console and just return or in test raise exception
  3158. if reraise:
  3159. raise e
  3160. finally:
  3161. if no_echo is False:
  3162. self.shell.close_proccessing()
  3163. pass
  3164. return result
  3165. # """
  3166. # Code below is unsused. Saved for later.
  3167. # """
  3168. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  3169. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  3170. # self.log.debug(parts)
  3171. # try:
  3172. # if parts[0] not in commands:
  3173. # self.shell.append_error("Unknown command\n")
  3174. # return
  3175. #
  3176. # #import inspect
  3177. # #inspect.getargspec(someMethod)
  3178. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  3179. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  3180. # self.shell.append_error(
  3181. # "Command %s takes %d arguments. %d given.\n" %
  3182. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  3183. # )
  3184. # return
  3185. #
  3186. # cmdfcn = commands[parts[0]]["fcn"]
  3187. # cmdconv = commands[parts[0]]["converters"]
  3188. # if len(parts) - 1 > 0:
  3189. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  3190. # else:
  3191. # retval = cmdfcn()
  3192. # retfcn = commands[parts[0]]["retfcn"]
  3193. # if retval and retfcn(retval):
  3194. # self.shell.append_output(retfcn(retval) + "\n")
  3195. #
  3196. # except Exception as e:
  3197. # #self.shell.append_error(''.join(traceback.format_exc()))
  3198. # #self.shell.append_error("?\n")
  3199. # self.shell.append_error(str(e) + "\n")
  3200. def info(self, msg):
  3201. """
  3202. Informs the user. Normally on the status bar, optionally
  3203. also on the shell.
  3204. :param msg: Text to write.
  3205. :return: None
  3206. """
  3207. # Type of message in brackets at the beginning of the message.
  3208. match = re.search("\[([^\]]+)\](.*)", msg)
  3209. if match:
  3210. level = match.group(1)
  3211. msg_ = match.group(2)
  3212. self.ui.fcinfo.set_status(str(msg_), level=level)
  3213. if level.lower() == "error":
  3214. self.shell_message(msg, error=True, show=True)
  3215. elif level.lower() == "warning":
  3216. self.shell_message(msg, warning=True, show=True)
  3217. elif level.lower() == "error_notcl":
  3218. self.shell_message(msg, error=True, show=False)
  3219. elif level.lower() == "warning_notcl":
  3220. self.shell_message(msg, warning=True, show=False)
  3221. elif level.lower() == "success":
  3222. self.shell_message(msg, success=True, show=False)
  3223. elif level.lower() == "selected":
  3224. self.shell_message(msg, selected=True, show=False)
  3225. else:
  3226. self.shell_message(msg, show=False)
  3227. else:
  3228. self.ui.fcinfo.set_status(str(msg), level="info")
  3229. # make sure that if the message is to clear the infobar with a space
  3230. # is not printed over and over on the shell
  3231. if msg != '':
  3232. self.shell_message(msg)
  3233. def restore_toolbar_view(self):
  3234. """
  3235. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  3236. was saved in the defaults dictionary.
  3237. :return: None
  3238. """
  3239. tb = self.defaults["global_toolbar_view"]
  3240. if tb & 1:
  3241. self.ui.toolbarfile.setVisible(True)
  3242. else:
  3243. self.ui.toolbarfile.setVisible(False)
  3244. if tb & 2:
  3245. self.ui.toolbargeo.setVisible(True)
  3246. else:
  3247. self.ui.toolbargeo.setVisible(False)
  3248. if tb & 4:
  3249. self.ui.toolbarview.setVisible(True)
  3250. else:
  3251. self.ui.toolbarview.setVisible(False)
  3252. if tb & 8:
  3253. self.ui.toolbartools.setVisible(True)
  3254. else:
  3255. self.ui.toolbartools.setVisible(False)
  3256. if tb & 16:
  3257. self.ui.exc_edit_toolbar.setVisible(True)
  3258. else:
  3259. self.ui.exc_edit_toolbar.setVisible(False)
  3260. if tb & 32:
  3261. self.ui.geo_edit_toolbar.setVisible(True)
  3262. else:
  3263. self.ui.geo_edit_toolbar.setVisible(False)
  3264. if tb & 64:
  3265. self.ui.grb_edit_toolbar.setVisible(True)
  3266. else:
  3267. self.ui.grb_edit_toolbar.setVisible(False)
  3268. if tb & 128:
  3269. self.ui.snap_toolbar.setVisible(True)
  3270. else:
  3271. self.ui.snap_toolbar.setVisible(False)
  3272. if tb & 256:
  3273. self.ui.toolbarshell.setVisible(True)
  3274. else:
  3275. self.ui.toolbarshell.setVisible(False)
  3276. def load_defaults(self, filename):
  3277. """
  3278. Loads the aplication's default settings from current_defaults.FlatConfig into
  3279. ``self.defaults``.
  3280. :return: None
  3281. """
  3282. try:
  3283. f = open(self.data_path + "/" + filename + ".FlatConfig")
  3284. options = f.read()
  3285. f.close()
  3286. except IOError:
  3287. self.log.error("Could not load defaults file.")
  3288. self.inform.emit('[ERROR] %s' %
  3289. _("Could not load defaults file."))
  3290. # in case the defaults file can't be loaded, show all toolbars
  3291. self.defaults["global_toolbar_view"] = 511
  3292. return
  3293. try:
  3294. defaults = json.loads(options)
  3295. except:
  3296. # in case the defaults file can't be loaded, show all toolbars
  3297. self.defaults["global_toolbar_view"] = 511
  3298. e = sys.exc_info()[0]
  3299. App.log.error(str(e))
  3300. self.inform.emit('[ERROR] %s' %
  3301. _("Failed to parse defaults file."))
  3302. return
  3303. self.defaults.update(defaults)
  3304. log.debug("FlatCAM defaults loaded from: %s" % filename)
  3305. # restore the toolbar view
  3306. self.restore_toolbar_view()
  3307. def on_import_preferences(self):
  3308. """
  3309. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  3310. ``self.defaults``.
  3311. :return: None
  3312. """
  3313. self.report_usage("on_import_preferences")
  3314. App.log.debug("on_import_preferences()")
  3315. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  3316. try:
  3317. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3318. directory=self.data_path,
  3319. filter=filter_)
  3320. except TypeError:
  3321. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3322. filter=filter_)
  3323. filename = str(filename)
  3324. if filename == "":
  3325. self.inform.emit('[WARNING_NOTCL] %s' %
  3326. _("FlatCAM preferences import cancelled."))
  3327. else:
  3328. try:
  3329. f = open(filename)
  3330. options = f.read()
  3331. f.close()
  3332. except IOError:
  3333. self.log.error("Could not load defaults file.")
  3334. self.inform.emit('[ERROR_NOTCL] %s' %
  3335. _("Could not load defaults file."))
  3336. return
  3337. try:
  3338. defaults_from_file = json.loads(options)
  3339. except Exception as e:
  3340. e = sys.exc_info()[0]
  3341. App.log.error(str(e))
  3342. self.inform.emit('[ERROR_NOTCL] %s' %
  3343. _("Failed to parse defaults file."))
  3344. return
  3345. self.defaults.update(defaults_from_file)
  3346. self.on_preferences_edited()
  3347. self.inform.emit('[success] %s: %s' %
  3348. (_("Imported Defaults from"), filename))
  3349. def on_export_preferences(self):
  3350. """
  3351. Save the defaults dictionary to a file.
  3352. :return: None
  3353. """
  3354. self.report_usage("on_export_preferences")
  3355. App.log.debug("on_export_preferences()")
  3356. defaults_file_content = None
  3357. self.date = str(datetime.today()).rpartition('.')[0]
  3358. self.date = ''.join(c for c in self.date if c not in ':-')
  3359. self.date = self.date.replace(' ', '_')
  3360. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  3361. try:
  3362. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  3363. caption=_("Export FlatCAM Preferences"),
  3364. directory=self.data_path + '/preferences_' + self.date,
  3365. filter=filter__
  3366. )
  3367. except TypeError:
  3368. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  3369. filter=filter__)
  3370. filename = str(filename)
  3371. defaults_from_file = {}
  3372. if filename == "":
  3373. self.inform.emit('[WARNING_NOTCL] %s' %
  3374. _("FlatCAM preferences export cancelled."))
  3375. return
  3376. else:
  3377. try:
  3378. f = open(filename, 'w')
  3379. defaults_file_content = f.read()
  3380. f.close()
  3381. except PermissionError:
  3382. self.inform.emit('[WARNING] %s' %
  3383. _("Permission denied, saving not possible.\n"
  3384. "Most likely another app is holding the file open and not accessible."))
  3385. return
  3386. except IOError:
  3387. App.log.debug('Creating a new preferences file ...')
  3388. f = open(filename, 'w')
  3389. json.dump({}, f)
  3390. f.close()
  3391. except:
  3392. e = sys.exc_info()[0]
  3393. App.log.error("Could not load defaults file.")
  3394. App.log.error(str(e))
  3395. self.inform.emit('[ERROR_NOTCL] %s' %
  3396. _("Could not load preferences file."))
  3397. return
  3398. try:
  3399. defaults_from_file = json.loads(defaults_file_content)
  3400. except:
  3401. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3402. # Update options
  3403. self.defaults_read_form()
  3404. defaults_from_file.update(self.defaults)
  3405. self.propagate_defaults(silent=True)
  3406. # Save update options
  3407. try:
  3408. f = open(filename, "w")
  3409. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3410. f.close()
  3411. except:
  3412. self.inform.emit('[ERROR_NOTCL] %s' %
  3413. _("Failed to write defaults to file."))
  3414. return
  3415. if self.defaults["global_open_style"] is False:
  3416. self.file_opened.emit("preferences", filename)
  3417. self.file_saved.emit("preferences", filename)
  3418. self.inform.emit('[success] %s: %s' %
  3419. (_("Exported preferences to"), filename))
  3420. def on_preferences_open_folder(self):
  3421. """
  3422. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  3423. :return: None
  3424. """
  3425. self.report_usage("on_preferences_open_folder()")
  3426. if sys.platform == 'win32':
  3427. subprocess.Popen('explorer %s' % self.data_path)
  3428. elif sys.platform == 'darwin':
  3429. os.system('open "%s"' % self.data_path)
  3430. else:
  3431. subprocess.Popen(['xdg-open', self.data_path])
  3432. self.inform.emit('[success] %s' %
  3433. _("FlatCAM Preferences Folder opened."))
  3434. def save_geometry(self, x, y, width, height, notebook_width):
  3435. """
  3436. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3437. launch of the application.
  3438. :param x: X position of the main window
  3439. :param y: Y position of the main window
  3440. :param width: width of the main window
  3441. :param height: height of the main window
  3442. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3443. :return: None
  3444. """
  3445. self.defaults["global_def_win_x"] = x
  3446. self.defaults["global_def_win_y"] = y
  3447. self.defaults["global_def_win_w"] = width
  3448. self.defaults["global_def_win_h"] = height
  3449. self.defaults["global_def_notebook_width"] = notebook_width
  3450. self.save_defaults()
  3451. def restore_main_win_geom(self):
  3452. try:
  3453. self.ui.setGeometry(self.defaults["global_def_win_x"],
  3454. self.defaults["global_def_win_y"],
  3455. self.defaults["global_def_win_w"],
  3456. self.defaults["global_def_win_h"])
  3457. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  3458. except KeyError as e:
  3459. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  3460. def message_dialog(self, title, message, kind="info"):
  3461. """
  3462. Builds and show a custom QMessageBox to be used in FlatCAM.
  3463. :param title: title of the QMessageBox
  3464. :param message: message to be displayed
  3465. :param kind: type of QMessageBox; will display a specific icon.
  3466. :return:
  3467. """
  3468. icon = {"info": QtWidgets.QMessageBox.Information,
  3469. "warning": QtWidgets.QMessageBox.Warning,
  3470. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3471. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3472. dlg.setText(message)
  3473. dlg.exec_()
  3474. def register_recent(self, kind, filename):
  3475. """
  3476. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3477. dictionary.
  3478. :param kind: type of file that was opened
  3479. :param filename: the path and file name for the file that was opened
  3480. :return:
  3481. """
  3482. self.log.debug("register_recent()")
  3483. self.log.debug(" %s" % kind)
  3484. self.log.debug(" %s" % filename)
  3485. record = {'kind': str(kind), 'filename': str(filename)}
  3486. if record in self.recent:
  3487. return
  3488. if record in self.recent_projects:
  3489. return
  3490. if record['kind'] == 'project':
  3491. self.recent_projects.insert(0, record)
  3492. else:
  3493. self.recent.insert(0, record)
  3494. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3495. self.recent.pop()
  3496. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3497. self.recent_projects.pop()
  3498. try:
  3499. f = open(self.data_path + '/recent.json', 'w')
  3500. except IOError:
  3501. App.log.error("Failed to open recent items file for writing.")
  3502. self.inform.emit('[ERROR_NOTCL] %s' %
  3503. _('Failed to open recent files file for writing.'))
  3504. return
  3505. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3506. f.close()
  3507. try:
  3508. fp = open(self.data_path + '/recent_projects.json', 'w')
  3509. except IOError:
  3510. App.log.error("Failed to open recent items file for writing.")
  3511. self.inform.emit('[ERROR_NOTCL] %s' %
  3512. _('Failed to open recent projects file for writing.'))
  3513. return
  3514. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3515. fp.close()
  3516. # Re-build the recent items menu
  3517. self.setup_recent_items()
  3518. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3519. """
  3520. Creates a new specialized FlatCAMObj and attaches it to the application,
  3521. this is, updates the GUI accordingly, any other records and plots it.
  3522. This method is thread-safe.
  3523. Notes:
  3524. * If the name is in use, the self.collection will modify it
  3525. when appending it to the collection. There is no need to handle
  3526. name conflicts here.
  3527. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3528. :type kind: str
  3529. :param name: Name for the object.
  3530. :type name: str
  3531. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3532. The function is called with 2 parameters: the new object and the App instance.
  3533. :type initialize: function
  3534. :param active:
  3535. :param fit:
  3536. :param plot: If to plot the resulting object
  3537. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3538. self.colleaction
  3539. :return: None
  3540. :rtype: None
  3541. """
  3542. App.log.debug("new_object()")
  3543. obj_plot = plot
  3544. obj_autoselected = autoselected
  3545. t0 = time.time() # Debug
  3546. # ## Create object
  3547. classdict = {
  3548. "gerber": FlatCAMGerber,
  3549. "excellon": FlatCAMExcellon,
  3550. "cncjob": FlatCAMCNCjob,
  3551. "geometry": FlatCAMGeometry,
  3552. "script": FlatCAMScript,
  3553. "document": FlatCAMDocument
  3554. }
  3555. App.log.debug("Calling object constructor...")
  3556. obj = classdict[kind](name)
  3557. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3558. # Set options from "Project options" form
  3559. self.options_read_form()
  3560. # IMPORTANT
  3561. # The key names in defaults and options dictionary's are not random:
  3562. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3563. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  3564. # the options from project options form into the self.options. After that, below, depending on the type of
  3565. # object that is created, it will strip the name of the object and the underline (if the original key was
  3566. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3567. # "toolchange"
  3568. for option in self.options:
  3569. if option.find(kind + "_") == 0:
  3570. oname = option[len(kind) + 1:]
  3571. obj.options[oname] = self.options[option]
  3572. obj.isHovering = False
  3573. obj.notHovering = True
  3574. # Initialize as per user request
  3575. # User must take care to implement initialize
  3576. # in a thread-safe way as is is likely that we
  3577. # have been invoked in a separate thread.
  3578. t1 = time.time()
  3579. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3580. try:
  3581. return_value = initialize(obj, self)
  3582. except Exception as e:
  3583. msg = '[ERROR_NOTCL] %s' % \
  3584. _("An internal error has ocurred. See shell.\n")
  3585. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3586. msg += traceback.format_exc()
  3587. self.inform.emit(msg)
  3588. # if str(e) == "Empty Geometry":
  3589. # self.inform.emit("[ERROR_NOTCL] )
  3590. # else:
  3591. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3592. return "fail"
  3593. t2 = time.time()
  3594. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3595. if return_value == 'fail':
  3596. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3597. return "fail"
  3598. # Check units and convert if necessary
  3599. # This condition CAN be true because initialize() can change obj.units
  3600. if self.options["units"].upper() != obj.units.upper():
  3601. self.inform.emit('%s: %s' %
  3602. (_("Converting units to "), self.options["units"]))
  3603. obj.convert_units(self.options["units"])
  3604. t3 = time.time()
  3605. self.log.debug("%f seconds converting units." % (t3 - t2))
  3606. # Create the bounding box for the object and then add the results to the obj.options
  3607. # But not for Scripts or for Documents
  3608. if kind != 'document' and kind != 'script':
  3609. try:
  3610. xmin, ymin, xmax, ymax = obj.bounds()
  3611. obj.options['xmin'] = xmin
  3612. obj.options['ymin'] = ymin
  3613. obj.options['xmax'] = xmax
  3614. obj.options['ymax'] = ymax
  3615. except Exception as e:
  3616. log.warning("The object has no bounds properties. %s" % str(e))
  3617. return "fail"
  3618. # update the KeyWords list with the name of the file
  3619. self.myKeywords.append(obj.options['name'])
  3620. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3621. # Move the object to the main thread and let the app know that it is available.
  3622. obj.moveToThread(self.main_thread)
  3623. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3624. return obj
  3625. def new_excellon_object(self):
  3626. """
  3627. Creates a new, blank Excellon object.
  3628. :return: None
  3629. """
  3630. self.report_usage("new_excellon_object()")
  3631. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3632. def new_geometry_object(self):
  3633. """
  3634. Creates a new, blank and single-tool Geometry object.
  3635. :return: None
  3636. """
  3637. self.report_usage("new_geometry_object()")
  3638. def initialize(obj, self):
  3639. obj.multitool = False
  3640. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3641. def new_gerber_object(self):
  3642. """
  3643. Creates a new, blank Gerber object.
  3644. :return: None
  3645. """
  3646. self.report_usage("new_gerber_object()")
  3647. def initialize(grb_obj, self):
  3648. grb_obj.multitool = False
  3649. grb_obj.source_file = []
  3650. grb_obj.multigeo = False
  3651. grb_obj.follow = False
  3652. grb_obj.apertures = {}
  3653. grb_obj.solid_geometry = []
  3654. try:
  3655. grb_obj.options['xmin'] = 0
  3656. grb_obj.options['ymin'] = 0
  3657. grb_obj.options['xmax'] = 0
  3658. grb_obj.options['ymax'] = 0
  3659. except KeyError:
  3660. pass
  3661. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3662. def new_script_object(self, name=None, text=None):
  3663. """
  3664. Creates a new, blank TCL Script object.
  3665. :param name: a name for the new object
  3666. :return: None
  3667. """
  3668. self.report_usage("new_script_object()")
  3669. if text is not None:
  3670. new_source_file = text
  3671. else:
  3672. new_source_file = _(
  3673. "#\n"
  3674. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  3675. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  3676. "#\n\n"
  3677. "# FlatCAM commands list:\n"
  3678. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, "
  3679. "ClearCopper,\n"
  3680. "# Cncjob, Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, "
  3681. "GetNames,\n"
  3682. "# GetSys, ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillDrills,\n"
  3683. "# MillSlots, Mirror, New, NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"
  3684. "# Options, Paint, Panelize, Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, "
  3685. "SubtractPoly,\n"
  3686. "# SubtractRectangle, Version, WriteGCode\n"
  3687. "#\n\n"
  3688. )
  3689. def initialize(obj, self):
  3690. obj.source_file = deepcopy(new_source_file)
  3691. if name is None:
  3692. outname = 'new_script'
  3693. else:
  3694. outname = name
  3695. self.new_object('script', outname, initialize, plot=False)
  3696. def new_document_object(self):
  3697. """
  3698. Creates a new, blank Document object.
  3699. :return: None
  3700. """
  3701. self.report_usage("new_document_object()")
  3702. def initialize(obj, self):
  3703. obj.source_file = ""
  3704. self.new_object('document', 'new_document', initialize, plot=False)
  3705. def on_object_created(self, obj, plot, autoselect):
  3706. """
  3707. Event callback for object creation.
  3708. It will add the new object to the collection. After that it will plot the object in a threaded way
  3709. :param obj: The newly created FlatCAM object.
  3710. :param plot: if the newly create object t obe plotted
  3711. :param autoselect: if the newly created object to be autoselected after creation
  3712. :return: None
  3713. """
  3714. t0 = time.time() # DEBUG
  3715. self.log.debug("on_object_created()")
  3716. # The Collection might change the name if there is a collision
  3717. self.collection.append(obj)
  3718. # after adding the object to the collection always update the list of objects that are in the collection
  3719. self.all_objects_list = self.collection.get_list()
  3720. # self.inform.emit('[selected] %s created & selected: %s' %
  3721. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3722. if obj.kind == 'gerber':
  3723. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3724. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3725. elif obj.kind == 'excellon':
  3726. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3727. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3728. elif obj.kind == 'cncjob':
  3729. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3730. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3731. elif obj.kind == 'geometry':
  3732. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3733. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3734. elif obj.kind == 'script':
  3735. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3736. kind=obj.kind.capitalize(), color='orange', name=str(obj.options['name'])))
  3737. elif obj.kind == 'document':
  3738. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3739. kind=obj.kind.capitalize(), color='darkCyan', name=str(obj.options['name'])))
  3740. # update the SHELL auto-completer model with the name of the new object
  3741. self.shell._edit.set_model_data(self.myKeywords)
  3742. if autoselect:
  3743. # select the just opened object but deselect the previous ones
  3744. self.collection.set_all_inactive()
  3745. self.collection.set_active(obj.options["name"])
  3746. else:
  3747. self.collection.set_all_inactive()
  3748. # here it is done the object plotting
  3749. def worker_task(t_obj):
  3750. with self.proc_container.new(_("Plotting")):
  3751. if isinstance(t_obj, FlatCAMCNCjob):
  3752. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3753. else:
  3754. t_obj.plot()
  3755. t1 = time.time() # DEBUG
  3756. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3757. self.object_plotted.emit(t_obj)
  3758. # Send to worker
  3759. # self.worker.add_task(worker_task, [self])
  3760. if plot is True:
  3761. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3762. def on_object_changed(self, obj):
  3763. """
  3764. Called whenever the geometry of the object was changed in some way.
  3765. This require the update of it's bounding values so it can be the selected on canvas.
  3766. Update the bounding box data from obj.options
  3767. :param obj: the object that was changed
  3768. :return: None
  3769. """
  3770. xmin, ymin, xmax, ymax = obj.bounds()
  3771. obj.options['xmin'] = xmin
  3772. obj.options['ymin'] = ymin
  3773. obj.options['xmax'] = xmax
  3774. obj.options['ymax'] = ymax
  3775. log.debug("Object changed, updating the bounding box data on self.options")
  3776. # delete the old selection shape
  3777. self.delete_selection_shape()
  3778. self.should_we_save = True
  3779. def on_object_plotted(self, obj):
  3780. """
  3781. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3782. :param obj: object to be fit into view
  3783. :return: None
  3784. """
  3785. self.on_zoom_fit(None)
  3786. def options_read_form(self):
  3787. """
  3788. Same as it's equivalent from the defaults.
  3789. self.options use to store the preferences per project. No longer used.
  3790. :return: None
  3791. """
  3792. for option in self.options_form_fields:
  3793. self.options[option] = self.options_form_fields[option].get_value()
  3794. def options_write_form(self):
  3795. """
  3796. Same as it's equivalent from the defaults.
  3797. self.options use to store the preferences per project. No longer used.
  3798. :return: None
  3799. """
  3800. for option in self.options:
  3801. self.options_write_form_field(option)
  3802. def options_write_form_field(self, field):
  3803. """
  3804. Same as it's equivalent from the defaults.
  3805. self.options use to store the preferences per project. No longer used.
  3806. :return: None
  3807. """
  3808. try:
  3809. self.options_form_fields[field].set_value(self.options[field])
  3810. except KeyError:
  3811. # Changed from error to debug. This allows to have data stored
  3812. # which is not user-editable.
  3813. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  3814. pass
  3815. def on_about(self):
  3816. """
  3817. Displays the "about" dialog found in the Menu --> Help.
  3818. :return: None
  3819. """
  3820. self.report_usage("on_about")
  3821. version = self.version
  3822. version_date = self.version_date
  3823. beta = self.beta
  3824. class AboutDialog(QtWidgets.QDialog):
  3825. def __init__(self, parent=None):
  3826. QtWidgets.QDialog.__init__(self, parent)
  3827. # Icon and title
  3828. self.setWindowIcon(parent.app_icon)
  3829. self.setWindowTitle(_("About FlatCAM"))
  3830. self.resize(600, 200)
  3831. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3832. # self.setStyleSheet(
  3833. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3834. # "background-attachment: fixed"
  3835. # )
  3836. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3837. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3838. # palette = QtGui.QPalette()
  3839. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3840. # self.setPalette(palette)
  3841. logo = QtWidgets.QLabel()
  3842. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3843. title = QtWidgets.QLabel(
  3844. "<font size=8><B>FlatCAM</B></font><BR>"
  3845. "{title}<BR>"
  3846. "<BR>"
  3847. "<BR>"
  3848. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3849. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3850. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3851. "<B>{issue}</B></a><BR>".format(
  3852. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3853. devel=_("Development"),
  3854. down=_("DOWNLOAD"),
  3855. issue=_("Issue tracker"))
  3856. )
  3857. title.setOpenExternalLinks(True)
  3858. closebtn = QtWidgets.QPushButton(_("Close"))
  3859. tab_widget = QtWidgets.QTabWidget()
  3860. description_label = QtWidgets.QLabel(
  3861. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3862. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3863. version=version,
  3864. beta=('BETA' if beta else ''),
  3865. date=version_date,
  3866. arch=platform.architecture()[0])
  3867. )
  3868. description_label.setOpenExternalLinks(True)
  3869. lic_lbl_header = QtWidgets.QLabel(
  3870. '%s:<br>%s<br>' % (
  3871. _('Licensed under the MIT license'),
  3872. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  3873. "http://www.opensource.org/licenses/mit-license.php</a>"
  3874. )
  3875. )
  3876. lic_lbl_header.setOpenExternalLinks(True)
  3877. lic_lbl_body = QtWidgets.QLabel(
  3878. _(
  3879. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3880. 'of this software and associated documentation files (the "Software"), to deal\n'
  3881. 'in the Software without restriction, including without limitation the rights\n'
  3882. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3883. 'copies of the Software, and to permit persons to whom the Software is\n'
  3884. 'furnished to do so, subject to the following conditions:\n\n'
  3885. 'The above copyright notice and this permission notice shall be included in\n'
  3886. 'all copies or substantial portions of the Software.\n\n'
  3887. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3888. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3889. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3890. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3891. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3892. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3893. 'THE SOFTWARE.'
  3894. )
  3895. )
  3896. attributions_label = QtWidgets.QLabel(
  3897. _(
  3898. 'Some of the icons used are from the following sources:<br>'
  3899. '<div>Icons made by <a href="https://www.flaticon.com/authors/freepik" '
  3900. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  3901. 'title="Flaticon">www.flaticon.com</a></div>'
  3902. 'Icons by <a target="_blank" href="https://icons8.com">Icons8</a>'
  3903. )
  3904. )
  3905. # layouts
  3906. layout1 = QtWidgets.QVBoxLayout()
  3907. layout1_1 = QtWidgets.QHBoxLayout()
  3908. layout1_2 = QtWidgets.QHBoxLayout()
  3909. layout2 = QtWidgets.QHBoxLayout()
  3910. layout3 = QtWidgets.QHBoxLayout()
  3911. self.setLayout(layout1)
  3912. layout1.addLayout(layout1_1)
  3913. layout1.addLayout(layout1_2)
  3914. layout1.addLayout(layout2)
  3915. layout1.addLayout(layout3)
  3916. layout1_1.addStretch()
  3917. layout1_1.addWidget(description_label)
  3918. layout1_2.addWidget(tab_widget)
  3919. self.splash_tab = QtWidgets.QWidget()
  3920. self.splash_tab.setObjectName("splash_about")
  3921. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3922. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3923. tab_widget.addTab(self.splash_tab, _("Splash"))
  3924. self.programmmers_tab = QtWidgets.QWidget()
  3925. self.programmmers_tab.setObjectName("programmers_about")
  3926. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3927. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3928. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3929. self.translators_tab = QtWidgets.QWidget()
  3930. self.translators_tab.setObjectName("translators_about")
  3931. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3932. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3933. tab_widget.addTab(self.translators_tab, _("Translators"))
  3934. self.license_tab = QtWidgets.QWidget()
  3935. self.license_tab.setObjectName("license_about")
  3936. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3937. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3938. tab_widget.addTab(self.license_tab, _("License"))
  3939. self.attributions_tab = QtWidgets.QWidget()
  3940. self.attributions_tab.setObjectName("attributions_about")
  3941. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  3942. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  3943. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  3944. self.splash_tab_layout.addWidget(logo, stretch=0)
  3945. self.splash_tab_layout.addWidget(title, stretch=1)
  3946. pal = QtGui.QPalette()
  3947. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3948. self.prog_grid_lay = QtWidgets.QGridLayout()
  3949. self.prog_grid_lay.setHorizontalSpacing(20)
  3950. self.prog_grid_lay.setColumnStretch(0, 0)
  3951. self.prog_grid_lay.setColumnStretch(2, 1)
  3952. prog_widget = QtWidgets.QWidget()
  3953. prog_widget.setLayout(self.prog_grid_lay)
  3954. prog_scroll = QtWidgets.QScrollArea()
  3955. prog_scroll.setWidget(prog_widget)
  3956. prog_scroll.setWidgetResizable(True)
  3957. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3958. prog_scroll.setPalette(pal)
  3959. self.programmmers_tab_layout.addWidget(prog_scroll)
  3960. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  3961. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  3962. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3963. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  3964. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Program Author"), 1, 1)
  3965. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  3966. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  3967. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  3968. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  3969. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  3970. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  3971. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  3972. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 6, 0)
  3973. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  3974. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  3975. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  3976. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  3977. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 11, 0)
  3978. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  3979. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  3980. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 14, 0)
  3981. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 12, 0)
  3982. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 15, 0)
  3983. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 16, 0)
  3984. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 17, 0)
  3985. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 18, 0)
  3986. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 19, 0)
  3987. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 20, 0)
  3988. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 21, 0)
  3989. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 22, 0)
  3990. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 23, 0)
  3991. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 24, 0)
  3992. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 25, 0)
  3993. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 26, 0)
  3994. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 27, 0)
  3995. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 28, 0)
  3996. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 29, 0)
  3997. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 30, 0)
  3998. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 31, 0)
  3999. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 32, 0)
  4000. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 33, 0)
  4001. self.translator_grid_lay = QtWidgets.QGridLayout()
  4002. self.translator_grid_lay.setColumnStretch(0, 0)
  4003. self.translator_grid_lay.setColumnStretch(1, 0)
  4004. self.translator_grid_lay.setColumnStretch(2, 1)
  4005. self.translator_grid_lay.setColumnStretch(3, 0)
  4006. # trans_widget = QtWidgets.QWidget()
  4007. # trans_widget.setLayout(self.translator_grid_lay)
  4008. # self.translators_tab_layout.addWidget(trans_widget)
  4009. # self.translators_tab_layout.addStretch()
  4010. trans_widget = QtWidgets.QWidget()
  4011. trans_widget.setLayout(self.translator_grid_lay)
  4012. trans_scroll = QtWidgets.QScrollArea()
  4013. trans_scroll.setWidget(trans_widget)
  4014. trans_scroll.setWidgetResizable(True)
  4015. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  4016. trans_scroll.setPalette(pal)
  4017. self.translators_tab_layout.addWidget(trans_scroll)
  4018. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  4019. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  4020. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  4021. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  4022. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  4023. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  4024. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  4025. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  4026. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 2, 1)
  4027. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "(Google-Translation)"), 2, 2)
  4028. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  4029. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  4030. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 3, 1)
  4031. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt"), 3, 2)
  4032. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  4033. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  4034. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  4035. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 3)
  4036. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  4037. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  4038. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 3)
  4039. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  4040. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  4041. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "(Google-Translation)"), 6, 2)
  4042. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 3)
  4043. self.translator_grid_lay.setColumnStretch(0, 0)
  4044. self.translators_tab_layout.addStretch()
  4045. self.license_tab_layout.addWidget(lic_lbl_header)
  4046. self.license_tab_layout.addWidget(lic_lbl_body)
  4047. self.license_tab_layout.addStretch()
  4048. self.attributions_tab_layout.addWidget(attributions_label)
  4049. self.attributions_tab_layout.addStretch()
  4050. layout3.addStretch()
  4051. layout3.addWidget(closebtn)
  4052. closebtn.clicked.connect(self.accept)
  4053. AboutDialog(self.ui).exec_()
  4054. def install_bookmarks(self, book_dict=None):
  4055. """
  4056. Install the bookmarks actions in the Help menu -> Bookmarks
  4057. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  4058. :return: None
  4059. """
  4060. if book_dict is None:
  4061. self.defaults["global_bookmarks"].update(
  4062. {
  4063. '1': ['FlatCAM', "http://flatcam.org"],
  4064. '2': ['Backup Site', ""]
  4065. }
  4066. )
  4067. else:
  4068. self.defaults["global_bookmarks"].clear()
  4069. self.defaults["global_bookmarks"].update(book_dict)
  4070. # first try to disconnect if somehow they get connected from elsewhere
  4071. for act in self.ui.menuhelp_bookmarks.actions():
  4072. try:
  4073. act.triggered.disconnect()
  4074. except TypeError:
  4075. pass
  4076. # clear all actions except the last one who is the Bookmark manager
  4077. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  4078. pass
  4079. else:
  4080. self.ui.menuhelp_bookmarks.removeAction(act)
  4081. bm_limit = int(self.defaults["global_bookmarks_limit"])
  4082. if self.defaults["global_bookmarks"]:
  4083. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  4084. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  4085. # the JSON is first making the keys as strings (therefore I have to use strings too
  4086. # or do the conversion :(
  4087. # )
  4088. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  4089. # the '10' entry jsut after '1' therefore ordering as strings
  4090. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  4091. key=lambda x: int(x[0]))
  4092. for entry, bookmark in sorted_bookmarks:
  4093. title = bookmark[0]
  4094. weblink = bookmark[1]
  4095. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  4096. act.setText(title)
  4097. act.setIcon(QtGui.QIcon('share/link16.png'))
  4098. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  4099. if title == 'Backup Site' and weblink == "":
  4100. act.triggered.connect(self.on_backup_site)
  4101. else:
  4102. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  4103. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  4104. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  4105. def on_bookmarks_manager(self):
  4106. """
  4107. Adds the bookmark manager in a Tab in Plot Area
  4108. :return:
  4109. """
  4110. for idx in range(self.ui.plot_tab_area.count()):
  4111. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  4112. # there can be only one instance of Bookmark Manager at one time
  4113. return
  4114. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  4115. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  4116. # add the tab if it was closed
  4117. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  4118. # delete the absolute and relative position and messages in the infobar
  4119. self.ui.position_label.setText("")
  4120. self.ui.rel_position_label.setText("")
  4121. # Switch plot_area to preferences page
  4122. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  4123. def on_backup_site(self):
  4124. msgbox = QtWidgets.QMessageBox()
  4125. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  4126. "1. FlatCAM.org website is down\n"
  4127. "2. Someone forked FlatCAM project and wants to point\n"
  4128. "to his own website\n\n"
  4129. "If you can't get any informations about FlatCAM beta\n"
  4130. "use the YouTube channel link from the Help menu."))
  4131. msgbox.setWindowTitle(_("Alternative website"))
  4132. msgbox.setWindowIcon(QtGui.QIcon('share/globe16.png'))
  4133. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  4134. msgbox.setDefaultButton(bt_yes)
  4135. msgbox.exec_()
  4136. # response = msgbox.clickedButton()
  4137. def on_file_savedefaults(self):
  4138. """
  4139. Callback for menu item File->Save Defaults. Saves application default options
  4140. ``self.defaults`` to current_defaults.FlatConfig.
  4141. :return: None
  4142. """
  4143. self.save_defaults()
  4144. # def on_app_exit(self):
  4145. # self.report_usage("on_app_exit()")
  4146. #
  4147. # if self.collection.get_list():
  4148. # msgbox = QtWidgets.QMessageBox()
  4149. # # msgbox.setText("<B>Save changes ...</B>")
  4150. # msgbox.setText("There are files/objects opened in FlatCAM. "
  4151. # "\n"
  4152. # "Do you want to Save the project?")
  4153. # msgbox.setWindowTitle("Save changes")
  4154. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4155. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  4156. # QtWidgets.QMessageBox.Cancel)
  4157. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  4158. #
  4159. # response = msgbox.exec_()
  4160. #
  4161. # if response == QtWidgets.QMessageBox.Yes:
  4162. # self.on_file_saveprojectas(thread=False)
  4163. # elif response == QtWidgets.QMessageBox.Cancel:
  4164. # return
  4165. # self.save_defaults()
  4166. # else:
  4167. # self.save_defaults()
  4168. # log.debug("Application defaults saved ... Exit event.")
  4169. # QtWidgets.qApp.quit()
  4170. def save_defaults(self, silent=False, data_path=None, first_time=False):
  4171. """
  4172. Saves application default options
  4173. ``self.defaults`` to current_defaults.FlatConfig file.
  4174. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  4175. used at the next launch of the application.
  4176. :param silent: whether to display a message in status bar or not; boolean
  4177. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  4178. When the application is portable it should be a mobile location.
  4179. :return: None
  4180. """
  4181. self.report_usage("save_defaults")
  4182. if data_path is None:
  4183. data_path = self.data_path
  4184. # Read options from file
  4185. try:
  4186. f = open(data_path + "/current_defaults.FlatConfig")
  4187. defaults_file_content = f.read()
  4188. f.close()
  4189. except:
  4190. e = sys.exc_info()[0]
  4191. App.log.error("Could not load defaults file.")
  4192. App.log.error(str(e))
  4193. self.inform.emit('[ERROR_NOTCL] %s' %
  4194. _("Could not load defaults file."))
  4195. return
  4196. try:
  4197. defaults = json.loads(defaults_file_content)
  4198. except:
  4199. e = sys.exc_info()[0]
  4200. App.log.error("Failed to parse defaults file.")
  4201. App.log.error(str(e))
  4202. self.inform.emit('[ERROR_NOTCL] %s' %
  4203. _("Failed to parse defaults file."))
  4204. return
  4205. # Update options
  4206. self.defaults_read_form()
  4207. defaults.update(self.defaults)
  4208. self.propagate_defaults(silent=True)
  4209. # Save the toolbar view
  4210. tb_status = 0
  4211. if self.ui.toolbarfile.isVisible():
  4212. tb_status += 1
  4213. if self.ui.toolbargeo.isVisible():
  4214. tb_status += 2
  4215. if self.ui.toolbarview.isVisible():
  4216. tb_status += 4
  4217. if self.ui.toolbartools.isVisible():
  4218. tb_status += 8
  4219. if self.ui.exc_edit_toolbar.isVisible():
  4220. tb_status += 16
  4221. if self.ui.geo_edit_toolbar.isVisible():
  4222. tb_status += 32
  4223. if self.ui.grb_edit_toolbar.isVisible():
  4224. tb_status += 64
  4225. if self.ui.snap_toolbar.isVisible():
  4226. tb_status += 128
  4227. if self.ui.toolbarshell.isVisible():
  4228. tb_status += 256
  4229. if first_time is False:
  4230. self.defaults["global_toolbar_view"] = tb_status
  4231. # Save update options
  4232. try:
  4233. f = open(data_path + "/current_defaults.FlatConfig", "w")
  4234. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  4235. f.close()
  4236. except Exception as e:
  4237. log.debug("App.save_defaults() --> %s" % str(e))
  4238. self.inform.emit(f'[ERROR_NOTCL] {_("Failed to write defaults to file.")}')
  4239. return
  4240. if not silent:
  4241. self.inform.emit(f'[success] {_("Preferences saved.")}')
  4242. def save_factory_defaults(self, silent_message=False, data_path=None):
  4243. """
  4244. Saves application factory default options
  4245. ``self.defaults`` to factory_defaults.FlatConfig.
  4246. It's a one time job done just after the first install.
  4247. :param silent_message: whether to display a message in status bar or not; boolean
  4248. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  4249. When the application is portable it should be a mobile location.
  4250. :return: None
  4251. """
  4252. self.report_usage("save_factory_defaults")
  4253. if data_path is None:
  4254. data_path = self.data_path
  4255. # Read options from file
  4256. try:
  4257. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  4258. factory_defaults_file_content = f_f_def.read()
  4259. f_f_def.close()
  4260. except:
  4261. e = sys.exc_info()[0]
  4262. App.log.error("Could not load factory defaults file.")
  4263. App.log.error(str(e))
  4264. self.inform.emit(f'[ERROR_NOTCL] {_("Could not load factory defaults file.")}')
  4265. return
  4266. try:
  4267. factory_defaults = json.loads(factory_defaults_file_content)
  4268. except:
  4269. e = sys.exc_info()[0]
  4270. App.log.error("Failed to parse factory defaults file.")
  4271. App.log.error(str(e))
  4272. self.inform.emit(f'[ERROR_NOTCL] {_("Failed to parse factory defaults file.")}')
  4273. return
  4274. # Update options
  4275. self.defaults_read_form()
  4276. factory_defaults.update(self.defaults)
  4277. self.propagate_defaults(silent=True)
  4278. # Save update options
  4279. try:
  4280. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  4281. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  4282. f_f_def_s.close()
  4283. except Exception as e:
  4284. log.debug(f"App.save_factory_default() save update --> {str(e)}")
  4285. self.inform.emit(f'[ERROR_NOTCL] {_("Failed to write factory defaults to file.")}')
  4286. return
  4287. if silent_message is False:
  4288. self.inform.emit(f'{_("Factory defaults saved.")}')
  4289. def final_save(self):
  4290. """
  4291. Callback for doing a preferences save to file whenever the application is about to quit.
  4292. If the project has changes, it will ask the user to save the project.
  4293. :return: None
  4294. """
  4295. if self.save_in_progress:
  4296. self.inform.emit(f'[WARNING_NOTCL] {_("Application is saving the project. Please wait ...")}')
  4297. return
  4298. if self.should_we_save and self.collection.get_list():
  4299. msgbox = QtWidgets.QMessageBox()
  4300. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  4301. "\n"
  4302. "Do you want to Save the project?"))
  4303. msgbox.setWindowTitle(_("Save changes"))
  4304. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4305. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4306. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4307. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4308. msgbox.setDefaultButton(bt_yes)
  4309. msgbox.exec_()
  4310. response = msgbox.clickedButton()
  4311. if response == bt_yes:
  4312. try:
  4313. self.trayIcon.hide()
  4314. except:
  4315. pass
  4316. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  4317. elif response == bt_no:
  4318. try:
  4319. self.trayIcon.hide()
  4320. except:
  4321. pass
  4322. self.quit_application()
  4323. elif response == bt_cancel:
  4324. return
  4325. else:
  4326. try:
  4327. self.trayIcon.hide()
  4328. except:
  4329. pass
  4330. self.quit_application()
  4331. def quit_application(self):
  4332. """
  4333. Called (as a pyslot or not) when the application is quit.
  4334. :return: None
  4335. """
  4336. self.save_defaults()
  4337. log.debug("App.final_save() --> App Defaults saved.")
  4338. if self.cmd_line_headless != 1:
  4339. # save app state to file
  4340. settings = QSettings("Open Source", "FlatCAM")
  4341. settings.setValue('saved_gui_state', self.ui.saveState())
  4342. settings.setValue('maximized_gui', self.ui.isMaximized())
  4343. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  4344. settings.setValue(
  4345. 'notebook_font_size',
  4346. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  4347. )
  4348. settings.setValue('axis_font_size',
  4349. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value())
  4350. settings.setValue(
  4351. 'textbox_font_size',
  4352. self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  4353. )
  4354. settings.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  4355. # This will write the setting to the platform specific storage.
  4356. del settings
  4357. log.debug("App.final_save() --> App UI state saved.")
  4358. QtWidgets.qApp.quit()
  4359. def on_portable_checked(self, state):
  4360. """
  4361. Callback called when the checkbox in Preferences GUI is checked.
  4362. It will set the application as portable by creating the preferences and recent files in the
  4363. 'config' folder found in the FlatCAM installation folder.
  4364. :param state: boolean, the state of the checkbox when clicked/checked
  4365. :return:
  4366. """
  4367. line_no = 0
  4368. data = None
  4369. if sys.platform != 'win32':
  4370. # this won't work in Linux or MacOS
  4371. return
  4372. # test if the app was frozen and choose the path for the configuration file
  4373. if getattr(sys, "frozen", False) is True:
  4374. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  4375. else:
  4376. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  4377. config_file = current_data_path + '\\configuration.txt'
  4378. try:
  4379. with open(config_file, 'r') as f:
  4380. try:
  4381. data = f.readlines()
  4382. except Exception as e:
  4383. log.debug('App.__init__() -->%s' % str(e))
  4384. return
  4385. except FileNotFoundError:
  4386. pass
  4387. for line in data:
  4388. line = line.strip('\n')
  4389. param = str(line).rpartition('=')
  4390. if param[0] == 'portable':
  4391. break
  4392. line_no += 1
  4393. if state:
  4394. data[line_no] = 'portable=True\n'
  4395. # create the new defauults files
  4396. # create current_defaults.FlatConfig file if there is none
  4397. try:
  4398. f = open(current_data_path + '/current_defaults.FlatConfig')
  4399. f.close()
  4400. except IOError:
  4401. App.log.debug('Creating empty current_defaults.FlatConfig')
  4402. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  4403. json.dump({}, f)
  4404. f.close()
  4405. # create factory_defaults.FlatConfig file if there is none
  4406. try:
  4407. f = open(current_data_path + '/factory_defaults.FlatConfig')
  4408. f.close()
  4409. except IOError:
  4410. App.log.debug('Creating empty factory_defaults.FlatConfig')
  4411. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  4412. json.dump({}, f)
  4413. f.close()
  4414. try:
  4415. f = open(current_data_path + '/recent.json')
  4416. f.close()
  4417. except IOError:
  4418. App.log.debug('Creating empty recent.json')
  4419. f = open(current_data_path + '/recent.json', 'w')
  4420. json.dump([], f)
  4421. f.close()
  4422. try:
  4423. fp = open(current_data_path + '/recent_projects.json')
  4424. fp.close()
  4425. except IOError:
  4426. App.log.debug('Creating empty recent_projects.json')
  4427. fp = open(current_data_path + '/recent_projects.json', 'w')
  4428. json.dump([], fp)
  4429. fp.close()
  4430. # save the current defaults to the new defaults file
  4431. self.save_defaults(silent=True, data_path=current_data_path)
  4432. self.save_factory_defaults(silent_message=True, data_path=current_data_path)
  4433. else:
  4434. data[line_no] = 'portable=False\n'
  4435. with open(config_file, 'w') as f:
  4436. f.writelines(data)
  4437. def on_toggle_shell(self):
  4438. """
  4439. Toggle shell: if is visible close it, if it is closed then open it
  4440. :return:
  4441. """
  4442. self.report_usage("on_toggle_shell()")
  4443. if self.ui.shell_dock.isVisible():
  4444. self.ui.shell_dock.hide()
  4445. else:
  4446. self.ui.shell_dock.show()
  4447. def on_register_files(self, obj_type=None):
  4448. """
  4449. Called whenever there is a need to register file extensions with FlatCAM.
  4450. Works only in Windows and should be called only when FlatCAM is run in Windows.
  4451. :param obj_type: the type of object to be register for.
  4452. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  4453. :return: None
  4454. """
  4455. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  4456. new_reg_path = 'Software\\Classes\\'
  4457. # find if the current user is admin
  4458. try:
  4459. is_admin = os.getuid() == 0
  4460. except AttributeError:
  4461. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  4462. if is_admin is True:
  4463. root_path = winreg.HKEY_LOCAL_MACHINE
  4464. else:
  4465. root_path = winreg.HKEY_CURRENT_USER
  4466. # create the keys
  4467. def set_reg(name, root_path, new_reg_path, value):
  4468. try:
  4469. winreg.CreateKey(root_path, new_reg_path)
  4470. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  4471. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  4472. return True
  4473. except WindowsError:
  4474. return False
  4475. # delete key in registry
  4476. def delete_reg(root_path, reg_path, key_to_del):
  4477. key_to_del_path = reg_path + key_to_del
  4478. try:
  4479. winreg.DeleteKey(root_path, key_to_del_path)
  4480. return True
  4481. except WindowsError:
  4482. return False
  4483. if obj_type is None or obj_type == 'excellon':
  4484. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4485. exc_list = [x for x in exc_list if x != '']
  4486. # register all keys in the Preferences window
  4487. for ext in exc_list:
  4488. new_k = new_reg_path + '.%s' % ext
  4489. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4490. # and unregister those that are no longer in the Preferences windows but are in the file
  4491. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  4492. if ext not in exc_list:
  4493. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4494. # now write the updated extensions to the self.defaults
  4495. # new_ext = ''
  4496. # for ext in exc_list:
  4497. # new_ext = new_ext + ext + ', '
  4498. # self.defaults["fa_excellon"] = new_ext
  4499. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  4500. if obj_type is None or obj_type == 'gcode':
  4501. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4502. gco_list = [x for x in gco_list if x != '']
  4503. # register all keys in the Preferences window
  4504. for ext in gco_list:
  4505. new_k = new_reg_path + '.%s' % ext
  4506. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4507. # and unregister those that are no longer in the Preferences windows but are in the file
  4508. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  4509. if ext not in gco_list:
  4510. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4511. # now write the updated extensions to the self.defaults
  4512. # new_ext = ''
  4513. # for ext in gco_list:
  4514. # new_ext = new_ext + ext + ', '
  4515. # self.defaults["fa_gcode"] = new_ext
  4516. self.inform.emit('[success] %s' %
  4517. _("Selected GCode file extensions registered with FlatCAM."))
  4518. if obj_type is None or obj_type == 'gerber':
  4519. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4520. grb_list = [x for x in grb_list if x != '']
  4521. # register all keys in the Preferences window
  4522. for ext in grb_list:
  4523. new_k = new_reg_path + '.%s' % ext
  4524. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4525. # and unregister those that are no longer in the Preferences windows but are in the file
  4526. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  4527. if ext not in grb_list:
  4528. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4529. # now write the updated extensions to the self.defaults
  4530. # new_ext = ''
  4531. # for ext in grb_list:
  4532. # new_ext = new_ext + ext + ', '
  4533. # self.defaults["fa_gerber"] = new_ext
  4534. self.inform.emit('[success] %s' %
  4535. _("Selected Gerber file extensions registered with FlatCAM."))
  4536. def add_extension(self, ext_type):
  4537. if ext_type == 'excellon':
  4538. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4539. if new_ext == '':
  4540. return
  4541. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4542. if new_ext in old_val:
  4543. return
  4544. old_val.append(new_ext)
  4545. old_val.sort()
  4546. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4547. if ext_type == 'gcode':
  4548. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4549. if new_ext == '':
  4550. return
  4551. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4552. if new_ext in old_val:
  4553. return
  4554. old_val.append(new_ext)
  4555. old_val.sort()
  4556. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4557. if ext_type == 'gerber':
  4558. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4559. if new_ext == '':
  4560. return
  4561. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4562. if new_ext in old_val:
  4563. return
  4564. old_val.append(new_ext)
  4565. old_val.sort()
  4566. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4567. if ext_type == 'keyword':
  4568. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4569. if new_kw == '':
  4570. return
  4571. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4572. if new_kw in old_val:
  4573. return
  4574. old_val.append(new_kw)
  4575. old_val.sort()
  4576. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4577. # update the self.myKeywords so the model is updated
  4578. self.autocomplete_kw_list = \
  4579. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4580. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4581. self.shell._edit.set_model_data(self.myKeywords)
  4582. def del_extension(self, ext_type):
  4583. if ext_type == 'excellon':
  4584. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4585. if new_ext == '':
  4586. return
  4587. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4588. if new_ext not in old_val:
  4589. return
  4590. old_val.remove(new_ext)
  4591. old_val.sort()
  4592. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4593. if ext_type == 'gcode':
  4594. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4595. if new_ext == '':
  4596. return
  4597. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4598. if new_ext not in old_val:
  4599. return
  4600. old_val.remove(new_ext)
  4601. old_val.sort()
  4602. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4603. if ext_type == 'gerber':
  4604. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4605. if new_ext == '':
  4606. return
  4607. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4608. if new_ext not in old_val:
  4609. return
  4610. old_val.remove(new_ext)
  4611. old_val.sort()
  4612. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4613. if ext_type == 'keyword':
  4614. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4615. if new_kw == '':
  4616. return
  4617. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4618. if new_kw not in old_val:
  4619. return
  4620. old_val.remove(new_kw)
  4621. old_val.sort()
  4622. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4623. # update the self.myKeywords so the model is updated
  4624. self.autocomplete_kw_list = \
  4625. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4626. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4627. self.shell._edit.set_model_data(self.myKeywords)
  4628. def restore_extensions(self, ext_type):
  4629. if ext_type == 'excellon':
  4630. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4631. # for the ability to open Excellon files with .txt extension
  4632. new_exc_list = deepcopy(self.exc_list)
  4633. try:
  4634. new_exc_list.remove('txt')
  4635. except ValueError:
  4636. pass
  4637. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4638. if ext_type == 'gcode':
  4639. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4640. if ext_type == 'gerber':
  4641. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4642. if ext_type == 'keyword':
  4643. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4644. # update the self.myKeywords so the model is updated
  4645. self.autocomplete_kw_list = self.default_keywords
  4646. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4647. self.shell._edit.set_model_data(self.myKeywords)
  4648. def delete_all_extensions(self, ext_type):
  4649. if ext_type == 'excellon':
  4650. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4651. if ext_type == 'gcode':
  4652. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4653. if ext_type == 'gerber':
  4654. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4655. if ext_type == 'keyword':
  4656. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4657. # update the self.myKeywords so the model is updated
  4658. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4659. self.shell._edit.set_model_data(self.myKeywords)
  4660. def on_edit_join(self, name=None):
  4661. """
  4662. Callback for Edit->Join. Joins the selected geometry objects into
  4663. a new one.
  4664. :return: None
  4665. """
  4666. self.report_usage("on_edit_join()")
  4667. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4668. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4669. geo_type_list = set()
  4670. objs = self.collection.get_selected()
  4671. if len(objs) < 2:
  4672. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4673. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4674. return 'fail'
  4675. for obj in objs:
  4676. geo_type_list.add(obj.multigeo)
  4677. # if len(geo_type_list) == 1 means that all list elements are the same
  4678. if len(geo_type_list) != 1:
  4679. self.inform.emit('[ERROR] %s' %
  4680. _("Failed join. The Geometry objects are of different types.\n"
  4681. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4682. "convert from one to another and retry joining \n"
  4683. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4684. "the result may not be what was expected. \n"
  4685. "Check the generated GCODE."))
  4686. return
  4687. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4688. if True in geo_type_list:
  4689. def initialize(obj, app):
  4690. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=True)
  4691. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4692. for v in obj.tools.values():
  4693. v['data']['name'] = obj_name_multi
  4694. self.new_object("geometry", obj_name_multi, initialize)
  4695. else:
  4696. def initialize(obj, app):
  4697. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=False)
  4698. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4699. for v in obj.tools.values():
  4700. v['data']['name'] = obj_name_single
  4701. self.new_object("geometry", obj_name_single, initialize)
  4702. self.should_we_save = True
  4703. def on_edit_join_exc(self):
  4704. """
  4705. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4706. a new Excellon.
  4707. :return: None
  4708. """
  4709. self.report_usage("on_edit_join_exc()")
  4710. objs = self.collection.get_selected()
  4711. for obj in objs:
  4712. if not isinstance(obj, FlatCAMExcellon):
  4713. self.inform.emit('[ERROR_NOTCL] %s' %
  4714. _("Failed. Excellon joining works only on Excellon objects."))
  4715. return
  4716. if len(objs) < 2:
  4717. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4718. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4719. return 'fail'
  4720. def initialize(obj, app):
  4721. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=obj)
  4722. self.new_object("excellon", 'Combo_Excellon', initialize)
  4723. self.should_we_save = True
  4724. def on_edit_join_grb(self):
  4725. """
  4726. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4727. a new Gerber object.
  4728. :return: None
  4729. """
  4730. self.report_usage("on_edit_join_grb()")
  4731. objs = self.collection.get_selected()
  4732. for obj in objs:
  4733. if not isinstance(obj, FlatCAMGerber):
  4734. self.inform.emit('[ERROR_NOTCL] %s' %
  4735. _("Failed. Gerber joining works only on Gerber objects."))
  4736. return
  4737. if len(objs) < 2:
  4738. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4739. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4740. return 'fail'
  4741. def initialize(obj, app):
  4742. FlatCAMGerber.merge(self, grb_list=objs, grb_final=obj)
  4743. self.new_object("gerber", 'Combo_Gerber', initialize)
  4744. self.should_we_save = True
  4745. def on_convert_singlegeo_to_multigeo(self):
  4746. """
  4747. Called for converting a Geometry object from single-geo to multi-geo.
  4748. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4749. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4750. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4751. the solid-geometry of that tool.
  4752. :return: None
  4753. """
  4754. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4755. obj = self.collection.get_active()
  4756. if obj is None:
  4757. self.inform.emit('[ERROR_NOTCL] %s' %
  4758. _("Failed. Select a Geometry Object and try again."))
  4759. return
  4760. if not isinstance(obj, FlatCAMGeometry):
  4761. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4762. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4763. return
  4764. obj.multigeo = True
  4765. for tooluid, dict_value in obj.tools.items():
  4766. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4767. if not isinstance(obj.solid_geometry, list):
  4768. obj.solid_geometry = [obj.solid_geometry]
  4769. obj.solid_geometry[:] = []
  4770. obj.plot()
  4771. self.should_we_save = True
  4772. self.inform.emit('[success] %s' %
  4773. _("A Geometry object was converted to MultiGeo type."))
  4774. def on_convert_multigeo_to_singlegeo(self):
  4775. """
  4776. Called for converting a Geometry object from multi-geo to single-geo.
  4777. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4778. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4779. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4780. the solid-geometry of that tool.
  4781. :return: None
  4782. """
  4783. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4784. obj = self.collection.get_active()
  4785. if obj is None:
  4786. self.inform.emit('[ERROR_NOTCL] %s' %
  4787. _("Failed. Select a Geometry Object and try again."))
  4788. return
  4789. if not isinstance(obj, FlatCAMGeometry):
  4790. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4791. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4792. return
  4793. obj.multigeo = False
  4794. total_solid_geometry = []
  4795. for tooluid, dict_value in obj.tools.items():
  4796. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4797. # clear the original geometry
  4798. dict_value['solid_geometry'][:] = []
  4799. obj.solid_geometry = deepcopy(total_solid_geometry)
  4800. obj.plot()
  4801. self.should_we_save = True
  4802. self.inform.emit('[success] %s' %
  4803. _("A Geometry object was converted to SingleGeo type."))
  4804. def on_options_dict_change(self, field):
  4805. """
  4806. Called whenever a key changed in the self.options dictionary. This dict was used to store the preferences of the
  4807. current project. This feature is no longer used.
  4808. :param field:
  4809. :return:
  4810. """
  4811. self.options_write_form_field(field)
  4812. if field == "units":
  4813. self.set_screen_units(self.options['units'])
  4814. def on_defaults_dict_change(self, field):
  4815. """
  4816. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4817. Edit -> Preferences tab window.
  4818. :param field: the key of the self.defaults dictionary that was changed.
  4819. :return: None
  4820. """
  4821. self.defaults_write_form_field(field)
  4822. if field == "units":
  4823. self.set_screen_units(self.defaults['units'])
  4824. def set_screen_units(self, units):
  4825. """
  4826. Set the FlatCAM units on the status bar.
  4827. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4828. :return: None
  4829. """
  4830. self.ui.units_label.setText("[" + units.lower() + "]")
  4831. def on_toggle_units(self, no_pref=False):
  4832. """
  4833. Callback for the Units radio-button change in the Preferences tab.
  4834. Changes the application's default units adn for the project too.
  4835. If changing the project's units, the change propagates to all of
  4836. the objects in the project.
  4837. :return: None
  4838. """
  4839. self.report_usage("on_toggle_units")
  4840. if self.toggle_units_ignore:
  4841. return
  4842. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4843. # If option is the same, then ignore
  4844. if new_units == self.defaults["units"].upper():
  4845. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4846. return
  4847. # Options to scale
  4848. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin', "gerber_isooverlap",
  4849. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  4850. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4851. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4852. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4853. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  4854. "excellon_editor_slot_lin_pitch",
  4855. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4856. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4857. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4858. "geometry_feedrate_probe", "geometry_startz",
  4859. 'cncjob_tooldia',
  4860. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4861. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  4862. "tools_2sided_drilldia", "tools_film_boundary",
  4863. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4864. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4865. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4866. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4867. "tools_transform_offset_y",
  4868. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4869. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4870. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4871. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4872. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  4873. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  4874. "tools_cr_h2h_val", "tools_cr_dh_val",
  4875. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance"]
  4876. def scale_options(sfactor):
  4877. for dim in dimensions:
  4878. if dim == 'excellon_toolchangexy':
  4879. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4880. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4881. coords_xy[0] *= sfactor
  4882. coords_xy[1] *= sfactor
  4883. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4884. elif dim == 'geometry_toolchangexy':
  4885. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4886. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4887. coords_xy[0] *= sfactor
  4888. coords_xy[1] *= sfactor
  4889. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4890. elif dim == 'geometry_cnctooldia':
  4891. tools_diameters = []
  4892. try:
  4893. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4894. tools_diameters = [eval(a) for a in tools_string if a != '']
  4895. except Exception as e:
  4896. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4897. self.options['geometry_cnctooldia'] = ''
  4898. for t in range(len(tools_diameters)):
  4899. tools_diameters[t] *= sfactor
  4900. self.options['geometry_cnctooldia'] += "%f," % tools_diameters[t]
  4901. elif dim == 'tools_ncctools':
  4902. ncctools = []
  4903. try:
  4904. tools_string = self.defaults["tools_ncctools"].split(",")
  4905. ncctools = [eval(a) for a in tools_string if a != '']
  4906. except Exception as e:
  4907. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4908. self.options['tools_ncctools'] = ''
  4909. for t in range(len(ncctools)):
  4910. ncctools[t] *= sfactor
  4911. self.options['tools_ncctools'] += "%f," % ncctools[t]
  4912. elif dim == 'tools_solderpaste_tools':
  4913. sptools = []
  4914. try:
  4915. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4916. sptools = [eval(a) for a in tools_string if a != '']
  4917. except Exception as e:
  4918. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4919. self.options['tools_solderpaste_tools'] = ""
  4920. for t in range(len(sptools)):
  4921. sptools[t] *= sfactor
  4922. self.options['tools_solderpaste_tools'] += "%f," % sptools[t]
  4923. elif dim == 'tools_solderpaste_xy_toolchange':
  4924. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4925. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4926. sp_coords[0] *= sfactor
  4927. sp_coords[1] *= sfactor
  4928. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  4929. elif dim == 'global_gridx' or dim == 'global_gridy':
  4930. if new_units == 'IN':
  4931. val = 0.1
  4932. try:
  4933. val = float(self.defaults[dim]) * sfactor
  4934. except Exception as e:
  4935. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4936. self.options[dim] = float('%.6f' % val)
  4937. else:
  4938. val = 0.1
  4939. try:
  4940. val = float(self.defaults[dim]) * sfactor
  4941. except Exception as e:
  4942. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4943. self.options[dim] = float('%.4f' % val)
  4944. else:
  4945. val = 0.1
  4946. if self.options[dim]:
  4947. try:
  4948. val = float(self.options[dim]) * sfactor
  4949. except Exception as e:
  4950. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  4951. self.options[dim] = val
  4952. def scale_defaults(sfactor):
  4953. for dim in dimensions:
  4954. if dim == 'excellon_toolchangexy':
  4955. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4956. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4957. coords_xy[0] *= sfactor
  4958. coords_xy[1] *= sfactor
  4959. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4960. elif dim == 'geometry_toolchangexy':
  4961. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4962. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4963. coords_xy[0] *= sfactor
  4964. coords_xy[1] *= sfactor
  4965. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4966. elif dim == 'geometry_cnctooldia':
  4967. tools_diameters = []
  4968. try:
  4969. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4970. tools_diameters = [eval(a) for a in tools_string if a != '']
  4971. except Exception as e:
  4972. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4973. self.defaults['geometry_cnctooldia'] = ''
  4974. for t in range(len(tools_diameters)):
  4975. tools_diameters[t] *= sfactor
  4976. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  4977. elif dim == 'tools_ncctools':
  4978. ncctools = []
  4979. try:
  4980. tools_string = self.defaults["tools_ncctools"].split(",")
  4981. ncctools = [eval(a) for a in tools_string if a != '']
  4982. except Exception as e:
  4983. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4984. self.defaults['tools_ncctools'] = ''
  4985. for t in range(len(ncctools)):
  4986. ncctools[t] *= sfactor
  4987. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  4988. elif dim == 'tools_solderpaste_tools':
  4989. sptools = []
  4990. try:
  4991. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4992. sptools = [eval(a) for a in tools_string if a != '']
  4993. except Exception as e:
  4994. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4995. self.defaults['tools_solderpaste_tools'] = ""
  4996. for t in range(len(sptools)):
  4997. sptools[t] *= sfactor
  4998. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  4999. elif dim == 'tools_solderpaste_xy_toolchange':
  5000. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  5001. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  5002. sp_coords[0] *= sfactor
  5003. sp_coords[1] *= sfactor
  5004. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  5005. elif dim == 'global_gridx' or dim == 'global_gridy':
  5006. if new_units == 'IN':
  5007. val = 0.1
  5008. try:
  5009. val = float(self.defaults[dim]) * sfactor
  5010. except Exception as e:
  5011. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  5012. self.defaults[dim] = float('%.6f' % val)
  5013. else:
  5014. val = 0.1
  5015. try:
  5016. val = float(self.defaults[dim]) * sfactor
  5017. except Exception as e:
  5018. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  5019. self.defaults[dim] = float('%.4f' % val)
  5020. else:
  5021. val = 0.1
  5022. if self.defaults[dim]:
  5023. try:
  5024. val = float(self.defaults[dim]) * sfactor
  5025. except Exception as e:
  5026. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  5027. self.defaults[dim] = val
  5028. # The scaling factor depending on choice of units.
  5029. factor = 1/25.4
  5030. if new_units == 'MM':
  5031. factor = 25.4
  5032. # Changing project units. Warn user.
  5033. msgbox = QtWidgets.QMessageBox()
  5034. msgbox.setWindowTitle(_("Toggle Units"))
  5035. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  5036. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5037. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  5038. "properties of all objects to be scaled accordingly.\nContinue?"))
  5039. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5040. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5041. msgbox.setDefaultButton(bt_ok)
  5042. msgbox.exec_()
  5043. response = msgbox.clickedButton()
  5044. if response == bt_ok:
  5045. if no_pref is False:
  5046. self.options_read_form()
  5047. scale_options(factor)
  5048. self.options_write_form()
  5049. self.defaults_read_form()
  5050. scale_defaults(factor)
  5051. self.defaults_write_form(fl_units=new_units)
  5052. # save the defaults to file, some may assume that the conversion is enough and it's not
  5053. self.on_save_button()
  5054. self.should_we_save = True
  5055. # change this only if the workspace is active
  5056. if self.defaults['global_workspace'] is True:
  5057. self.plotcanvas.draw_workspace()
  5058. # adjust the grid values on the main toolbar
  5059. dec = 6 if new_units == 'IN'else 4
  5060. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  5061. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  5062. if not self.ui.grid_gap_link_cb.isChecked():
  5063. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  5064. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  5065. for obj in self.collection.get_list():
  5066. obj.convert_units(new_units)
  5067. # make that the properties stored in the object are also updated
  5068. self.object_changed.emit(obj)
  5069. obj.build_ui()
  5070. current = self.collection.get_active()
  5071. if current is not None:
  5072. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  5073. if not isinstance(current, FlatCAMGeometry):
  5074. current.to_form()
  5075. self.plot_all()
  5076. self.inform.emit('[success] %s: %s' %
  5077. (_("Converted units to"), new_units))
  5078. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  5079. self.set_screen_units(new_units)
  5080. else:
  5081. # Undo toggling
  5082. self.toggle_units_ignore = True
  5083. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  5084. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  5085. else:
  5086. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  5087. self.toggle_units_ignore = False
  5088. self.inform.emit('[WARNING_NOTCL]%s' %
  5089. _(" Units conversion cancelled."))
  5090. self.options_read_form()
  5091. self.defaults_read_form()
  5092. def on_toggle_units_click(self):
  5093. try:
  5094. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  5095. except (TypeError, AttributeError):
  5096. pass
  5097. if self.defaults["units"] == 'MM':
  5098. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  5099. else:
  5100. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  5101. self.on_toggle_units(no_pref=True)
  5102. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  5103. lambda: self.on_toggle_units(no_pref=False))
  5104. def on_fullscreen(self, disable=False):
  5105. self.report_usage("on_fullscreen()")
  5106. if self.toggle_fscreen is False and disable is False:
  5107. # self.ui.showFullScreen()
  5108. self.ui.setWindowFlags(self.ui.windowFlags() | Qt.FramelessWindowHint)
  5109. a = self.ui.geometry()
  5110. self.x_pos = a.x()
  5111. self.y_pos = a.y()
  5112. self.width = a.width()
  5113. self.height = a.height()
  5114. # set new geometry to full desktop rect
  5115. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  5116. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  5117. # everything else will not work without this hack. This happen in Windows.
  5118. # https://bugreports.qt.io/browse/QTBUG-41309
  5119. desktop = QtWidgets.QApplication.desktop()
  5120. screen = desktop.screenNumber(QtGui.QCursor.pos())
  5121. rec = desktop.screenGeometry(screen)
  5122. x = rec.x() - 1
  5123. y = rec.y() - 1
  5124. h = rec.height() + 2
  5125. w = rec.width() + 2
  5126. self.ui.setGeometry(x, y, w, h)
  5127. self.ui.show()
  5128. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  5129. tb.setVisible(False)
  5130. self.ui.splitter_left.setVisible(False)
  5131. self.toggle_fscreen = True
  5132. elif self.toggle_fscreen is True or disable is True:
  5133. self.ui.setWindowFlags(self.ui.windowFlags() & ~Qt.FramelessWindowHint)
  5134. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  5135. self.ui.showNormal()
  5136. self.restore_toolbar_view()
  5137. self.ui.splitter_left.setVisible(True)
  5138. self.toggle_fscreen = False
  5139. def on_toggle_plotarea(self):
  5140. self.report_usage("on_toggle_plotarea()")
  5141. try:
  5142. name = self.ui.plot_tab_area.widget(0).objectName()
  5143. except AttributeError:
  5144. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  5145. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  5146. self.ui.plot_tab_area.protectTab(0)
  5147. return
  5148. if name != 'plotarea':
  5149. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5150. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  5151. self.ui.plot_tab_area.protectTab(0)
  5152. else:
  5153. self.ui.plot_tab_area.closeTab(0)
  5154. def on_toggle_notebook(self):
  5155. if self.ui.splitter.sizes()[0] == 0:
  5156. self.ui.splitter.setSizes([1, 1])
  5157. self.ui.menu_toggle_nb.setChecked(True)
  5158. else:
  5159. self.ui.splitter.setSizes([0, 1])
  5160. self.ui.menu_toggle_nb.setChecked(False)
  5161. def on_toggle_axis(self):
  5162. self.report_usage("on_toggle_axis()")
  5163. if self.toggle_axis is False:
  5164. if self.is_legacy is False:
  5165. # self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  5166. # self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  5167. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  5168. parent=self.plotcanvas.view.scene)
  5169. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  5170. parent=self.plotcanvas.view.scene)
  5171. # self.plotcanvas.redraw()
  5172. else:
  5173. self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  5174. self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  5175. self.plotcanvas.canvas.draw()
  5176. pass
  5177. self.toggle_axis = True
  5178. else:
  5179. if self.is_legacy is False:
  5180. # self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  5181. # self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  5182. # self.plotcanvas.redraw()
  5183. self.plotcanvas.v_line.parent = None
  5184. self.plotcanvas.h_line.parent = None
  5185. else:
  5186. self.plotcanvas.axes.lines[:] = []
  5187. self.plotcanvas.canvas.draw()
  5188. self.toggle_axis = False
  5189. def on_toggle_grid(self):
  5190. self.report_usage("on_toggle_grid()")
  5191. self.ui.grid_snap_btn.trigger()
  5192. def on_toggle_grid_lines(self):
  5193. self.report_usage("on_toggle_grd_lines()")
  5194. settings = QtCore.QSettings("Open Source", "FlatCAM")
  5195. if settings.contains("theme"):
  5196. theme = settings.value('theme', type=str)
  5197. else:
  5198. theme = 'white'
  5199. if self.toggle_grid_lines is False:
  5200. if self.is_legacy is False:
  5201. if theme == 'white':
  5202. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  5203. else:
  5204. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  5205. else:
  5206. self.plotcanvas.axes.grid(True)
  5207. try:
  5208. self.plotcanvas.canvas.draw()
  5209. except IndexError:
  5210. pass
  5211. pass
  5212. self.toggle_grid_lines = True
  5213. else:
  5214. if self.is_legacy is False:
  5215. if theme == 'white':
  5216. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  5217. else:
  5218. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  5219. else:
  5220. self.plotcanvas.axes.grid(False)
  5221. try:
  5222. self.plotcanvas.canvas.draw()
  5223. except IndexError:
  5224. pass
  5225. self.toggle_grid_lines = False
  5226. def on_options_combo_change(self, sel):
  5227. """
  5228. Called when the combo box to choose between application defaults and
  5229. project option changes value. The corresponding variables are
  5230. copied to the UI.
  5231. :param sel: The option index that was chosen.
  5232. :return: None
  5233. """
  5234. # combo_sel = self.ui.notebook.combo_options.get_active()
  5235. App.log.debug("Options --> %s" % sel)
  5236. # form = [self.defaults_form, self.options_form][sel]
  5237. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  5238. if sel == 0:
  5239. self.gen_form = self.ui.general_defaults_form
  5240. self.ger_form = self.ui.gerber_defaults_form
  5241. self.exc_form = self.ui.excellon_defaults_form
  5242. self.geo_form = self.ui.geometry_defaults_form
  5243. self.cnc_form = self.ui.cncjob_defaults_form
  5244. self.tools_form = self.ui.tools_defaults_form
  5245. self.tools2_form = self.ui.tools2_defaults_form
  5246. self.fa_form = self.ui.util_defaults_form
  5247. elif sel == 1:
  5248. self.gen_form = self.ui.general_options_form
  5249. self.ger_form = self.ui.gerber_options_form
  5250. self.exc_form = self.ui.excellon_options_form
  5251. self.geo_form = self.ui.geometry_options_form
  5252. self.cnc_form = self.ui.cncjob_options_form
  5253. self.tools_form = self.ui.tools_options_form
  5254. self.tools2_form = self.ui.tools2_options_form
  5255. self.fa_form = self.ui.util_options_form
  5256. else:
  5257. return
  5258. try:
  5259. self.ui.general_scroll_area.takeWidget()
  5260. except:
  5261. self.log.debug("Nothing to remove")
  5262. self.ui.general_scroll_area.setWidget(self.gen_form)
  5263. self.gen_form.show()
  5264. try:
  5265. self.ui.gerber_scroll_area.takeWidget()
  5266. except:
  5267. self.log.debug("Nothing to remove")
  5268. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  5269. self.ger_form.show()
  5270. try:
  5271. self.ui.excellon_scroll_area.takeWidget()
  5272. except:
  5273. self.log.debug("Nothing to remove")
  5274. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  5275. self.exc_form.show()
  5276. try:
  5277. self.ui.geometry_scroll_area.takeWidget()
  5278. except:
  5279. self.log.debug("Nothing to remove")
  5280. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  5281. self.geo_form.show()
  5282. try:
  5283. self.ui.cncjob_scroll_area.takeWidget()
  5284. except:
  5285. self.log.debug("Nothing to remove")
  5286. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  5287. self.cnc_form.show()
  5288. try:
  5289. self.ui.tools_scroll_area.takeWidget()
  5290. except:
  5291. self.log.debug("Nothing to remove")
  5292. self.ui.tools_scroll_area.setWidget(self.tools_form)
  5293. self.tools_form.show()
  5294. try:
  5295. self.ui.tools2_scroll_area.takeWidget()
  5296. except:
  5297. self.log.debug("Nothing to remove")
  5298. self.ui.tools2_scroll_area.setWidget(self.tools2_form)
  5299. self.tools2_form.show()
  5300. try:
  5301. self.ui.fa_scroll_area.takeWidget()
  5302. except:
  5303. self.log.debug("Nothing to remove")
  5304. self.ui.fa_scroll_area.setWidget(self.fa_form)
  5305. self.fa_form.show()
  5306. self.log.debug("Finished GUI form initialization.")
  5307. # self.options2form()
  5308. def on_excellon_defaults_button(self):
  5309. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  5310. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  5311. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  5312. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  5313. self.defaults_form_fields["excellon_zeros"].set_value('L')
  5314. self.defaults_form_fields["excellon_units"].set_value('INCH')
  5315. log.debug("Excellon app defaults loaded ...")
  5316. def on_excellon_options_button(self):
  5317. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  5318. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  5319. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  5320. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  5321. self.options_form_fields["excellon_zeros"].set_value('L')
  5322. self.options_form_fields["excellon_units"].set_value('INCH')
  5323. log.debug("Excellon options defaults loaded ...")
  5324. def on_update_exc_export(self, state):
  5325. """
  5326. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  5327. if the update_excellon_cb checkbox is checked
  5328. :param state: state of the checkbox whose signals is tied to his slot
  5329. :return:
  5330. """
  5331. if state:
  5332. # first try to disconnect
  5333. try:
  5334. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.\
  5335. disconnect(self.on_excellon_format_changed)
  5336. except TypeError:
  5337. pass
  5338. try:
  5339. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.\
  5340. disconnect(self.on_excellon_format_changed)
  5341. except TypeError:
  5342. pass
  5343. try:
  5344. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.\
  5345. disconnect(self.on_excellon_format_changed)
  5346. except TypeError:
  5347. pass
  5348. try:
  5349. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.\
  5350. disconnect(self.on_excellon_format_changed)
  5351. except TypeError:
  5352. pass
  5353. try:
  5354. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  5355. disconnect(self.on_excellon_zeros_changed)
  5356. except TypeError:
  5357. pass
  5358. try:
  5359. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  5360. disconnect(self.on_excellon_zeros_changed)
  5361. except TypeError:
  5362. pass
  5363. # the connect them
  5364. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  5365. self.on_excellon_format_changed)
  5366. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  5367. self.on_excellon_format_changed)
  5368. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  5369. self.on_excellon_format_changed)
  5370. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  5371. self.on_excellon_format_changed)
  5372. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  5373. self.on_excellon_zeros_changed)
  5374. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  5375. self.on_excellon_units_changed)
  5376. else:
  5377. # disconnect the signals
  5378. try:
  5379. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  5380. disconnect(self.on_excellon_format_changed)
  5381. except TypeError:
  5382. pass
  5383. try:
  5384. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  5385. disconnect(self.on_excellon_format_changed)
  5386. except TypeError:
  5387. pass
  5388. try:
  5389. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  5390. disconnect(self.on_excellon_format_changed)
  5391. except TypeError:
  5392. pass
  5393. try:
  5394. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  5395. disconnect(self.on_excellon_format_changed)
  5396. except TypeError:
  5397. pass
  5398. try:
  5399. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  5400. disconnect(self.on_excellon_zeros_changed)
  5401. except TypeError:
  5402. pass
  5403. try:
  5404. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  5405. disconnect(self.on_excellon_zeros_changed)
  5406. except TypeError:
  5407. pass
  5408. def on_excellon_format_changed(self):
  5409. """
  5410. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  5411. :return: None
  5412. """
  5413. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  5414. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5415. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  5416. )
  5417. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5418. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  5419. )
  5420. else:
  5421. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5422. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  5423. )
  5424. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5425. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  5426. )
  5427. def on_excellon_zeros_changed(self):
  5428. """
  5429. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  5430. :return: None
  5431. """
  5432. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  5433. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  5434. )
  5435. def on_excellon_units_changed(self):
  5436. """
  5437. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  5438. :return: None
  5439. """
  5440. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  5441. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  5442. )
  5443. self.on_excellon_format_changed()
  5444. # Setting plot colors handlers
  5445. def on_pf_color_entry(self):
  5446. self.defaults['global_plot_fill'] = \
  5447. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  5448. self.defaults['global_plot_fill'][7:9]
  5449. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5450. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  5451. def on_pf_color_button(self):
  5452. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  5453. c_dialog = QtWidgets.QColorDialog()
  5454. plot_fill_color = c_dialog.getColor(initial=current_color)
  5455. if plot_fill_color.isValid() is False:
  5456. return
  5457. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5458. "background-color:%s" % str(plot_fill_color.name()))
  5459. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  5460. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  5461. self.defaults['global_plot_fill'] = new_val
  5462. def on_pf_color_spinner(self):
  5463. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  5464. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  5465. self.defaults['global_plot_fill'] = \
  5466. self.defaults['global_plot_fill'][:7] + \
  5467. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5468. self.defaults['global_plot_line'] = \
  5469. self.defaults['global_plot_line'][:7] + \
  5470. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5471. def on_pf_color_slider(self):
  5472. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  5473. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  5474. def on_pl_color_entry(self):
  5475. self.defaults['global_plot_line'] = \
  5476. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  5477. self.defaults['global_plot_line'][7:9]
  5478. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5479. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  5480. def on_pl_color_button(self):
  5481. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  5482. # print(current_color)
  5483. c_dialog = QtWidgets.QColorDialog()
  5484. plot_line_color = c_dialog.getColor(initial=current_color)
  5485. if plot_line_color.isValid() is False:
  5486. return
  5487. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5488. "background-color:%s" % str(plot_line_color.name()))
  5489. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  5490. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  5491. self.defaults['global_plot_line'] = new_val_line
  5492. # Setting selection colors (left - right) handlers
  5493. def on_sf_color_entry(self):
  5494. self.defaults['global_sel_fill'] = \
  5495. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  5496. self.defaults['global_sel_fill'][7:9]
  5497. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5498. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  5499. def on_sf_color_button(self):
  5500. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  5501. c_dialog = QtWidgets.QColorDialog()
  5502. plot_fill_color = c_dialog.getColor(initial=current_color)
  5503. if plot_fill_color.isValid() is False:
  5504. return
  5505. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5506. "background-color:%s" % str(plot_fill_color.name()))
  5507. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  5508. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  5509. self.defaults['global_sel_fill'] = new_val
  5510. def on_sf_color_spinner(self):
  5511. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  5512. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  5513. self.defaults['global_sel_fill'] = \
  5514. self.defaults['global_sel_fill'][:7] + \
  5515. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5516. self.defaults['global_sel_line'] = \
  5517. self.defaults['global_sel_line'][:7] + \
  5518. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5519. def on_sf_color_slider(self):
  5520. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  5521. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  5522. def on_sl_color_entry(self):
  5523. self.defaults['global_sel_line'] = \
  5524. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  5525. self.defaults['global_sel_line'][7:9]
  5526. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5527. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  5528. def on_sl_color_button(self):
  5529. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  5530. c_dialog = QtWidgets.QColorDialog()
  5531. plot_line_color = c_dialog.getColor(initial=current_color)
  5532. if plot_line_color.isValid() is False:
  5533. return
  5534. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5535. "background-color:%s" % str(plot_line_color.name()))
  5536. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  5537. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  5538. self.defaults['global_sel_line'] = new_val_line
  5539. # Setting selection colors (right - left) handlers
  5540. def on_alt_sf_color_entry(self):
  5541. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  5542. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  5543. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5544. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  5545. def on_alt_sf_color_button(self):
  5546. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  5547. c_dialog = QtWidgets.QColorDialog()
  5548. plot_fill_color = c_dialog.getColor(initial=current_color)
  5549. if plot_fill_color.isValid() is False:
  5550. return
  5551. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5552. "background-color:%s" % str(plot_fill_color.name()))
  5553. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  5554. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  5555. self.defaults['global_alt_sel_fill'] = new_val
  5556. def on_alt_sf_color_spinner(self):
  5557. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  5558. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  5559. self.defaults['global_alt_sel_fill'] = \
  5560. self.defaults['global_alt_sel_fill'][:7] + \
  5561. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5562. self.defaults['global_alt_sel_line'] = \
  5563. self.defaults['global_alt_sel_line'][:7] + \
  5564. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5565. def on_alt_sf_color_slider(self):
  5566. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  5567. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  5568. def on_alt_sl_color_entry(self):
  5569. self.defaults['global_alt_sel_line'] = \
  5570. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  5571. self.defaults['global_alt_sel_line'][7:9]
  5572. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5573. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  5574. def on_alt_sl_color_button(self):
  5575. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  5576. c_dialog = QtWidgets.QColorDialog()
  5577. plot_line_color = c_dialog.getColor(initial=current_color)
  5578. if plot_line_color.isValid() is False:
  5579. return
  5580. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5581. "background-color:%s" % str(plot_line_color.name()))
  5582. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  5583. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  5584. self.defaults['global_alt_sel_line'] = new_val_line
  5585. # Setting Editor colors
  5586. def on_draw_color_entry(self):
  5587. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5588. .draw_color_entry.get_value()
  5589. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5590. "background-color:%s" % str(self.defaults['global_draw_color']))
  5591. def on_draw_color_button(self):
  5592. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  5593. c_dialog = QtWidgets.QColorDialog()
  5594. draw_color = c_dialog.getColor(initial=current_color)
  5595. if draw_color.isValid() is False:
  5596. return
  5597. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5598. "background-color:%s" % str(draw_color.name()))
  5599. new_val = str(draw_color.name())
  5600. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  5601. self.defaults['global_draw_color'] = new_val
  5602. def on_sel_draw_color_entry(self):
  5603. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5604. .sel_draw_color_entry.get_value()
  5605. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5606. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  5607. def on_sel_draw_color_button(self):
  5608. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  5609. c_dialog = QtWidgets.QColorDialog()
  5610. sel_draw_color = c_dialog.getColor(initial=current_color)
  5611. if sel_draw_color.isValid() is False:
  5612. return
  5613. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5614. "background-color:%s" % str(sel_draw_color.name()))
  5615. new_val_sel = str(sel_draw_color.name())
  5616. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  5617. self.defaults['global_sel_draw_color'] = new_val_sel
  5618. def on_proj_color_entry(self):
  5619. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  5620. .proj_color_entry.get_value()
  5621. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5622. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  5623. def on_proj_color_button(self):
  5624. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  5625. c_dialog = QtWidgets.QColorDialog()
  5626. proj_color = c_dialog.getColor(initial=current_color)
  5627. if proj_color.isValid() is False:
  5628. return
  5629. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5630. "background-color:%s" % str(proj_color.name()))
  5631. new_val_sel = str(proj_color.name())
  5632. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  5633. self.defaults['global_proj_item_color'] = new_val_sel
  5634. def on_proj_color_dis_entry(self):
  5635. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  5636. .proj_color_dis_entry.get_value()
  5637. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5638. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  5639. def on_proj_color_dis_button(self):
  5640. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  5641. c_dialog = QtWidgets.QColorDialog()
  5642. proj_color = c_dialog.getColor(initial=current_color)
  5643. if proj_color.isValid() is False:
  5644. return
  5645. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5646. "background-color:%s" % str(proj_color.name()))
  5647. new_val_sel = str(proj_color.name())
  5648. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  5649. self.defaults['global_proj_item_dis_color'] = new_val_sel
  5650. def on_annotation_fontcolor_entry(self):
  5651. self.defaults['cncjob_annotation_fontcolor'] = \
  5652. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.get_value()
  5653. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5654. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  5655. def on_annotation_fontcolor_button(self):
  5656. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  5657. c_dialog = QtWidgets.QColorDialog()
  5658. annotation_color = c_dialog.getColor(initial=current_color)
  5659. if annotation_color.isValid() is False:
  5660. return
  5661. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5662. "background-color:%s" % str(annotation_color.name()))
  5663. new_val_sel = str(annotation_color.name())
  5664. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(new_val_sel)
  5665. self.defaults['cncjob_annotation_fontcolor'] = new_val_sel
  5666. def on_film_color_entry(self):
  5667. self.defaults['tools_film_color'] = \
  5668. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5669. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5670. "background-color:%s" % str(self.defaults['tools_film_color']))
  5671. def on_film_color_button(self):
  5672. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5673. c_dialog = QtWidgets.QColorDialog()
  5674. film_color = c_dialog.getColor(initial=current_color)
  5675. if film_color.isValid() is False:
  5676. return
  5677. # if new color is different then mark that the Preferences are changed
  5678. if film_color != current_color:
  5679. self.on_preferences_edited()
  5680. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5681. "background-color:%s" % str(film_color.name()))
  5682. new_val_sel = str(film_color.name())
  5683. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5684. self.defaults['tools_film_color'] = new_val_sel
  5685. def on_qrcode_fill_color_entry(self):
  5686. self.defaults['tools_qrcode_fill_color'] = \
  5687. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  5688. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5689. "background-color:%s" % str(self.defaults['tools_qrcode_fill_color']))
  5690. def on_qrcode_fill_color_button(self):
  5691. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  5692. c_dialog = QtWidgets.QColorDialog()
  5693. fill_color = c_dialog.getColor(initial=current_color)
  5694. if fill_color.isValid() is False:
  5695. return
  5696. # if new color is different then mark that the Preferences are changed
  5697. if fill_color != current_color:
  5698. self.on_preferences_edited()
  5699. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5700. "background-color:%s" % str(fill_color.name()))
  5701. new_val_sel = str(fill_color.name())
  5702. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  5703. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  5704. def on_qrcode_back_color_entry(self):
  5705. self.defaults['tools_qrcode_back_color'] = \
  5706. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  5707. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5708. "background-color:%s" % str(self.defaults['tools_qrcode_back_color']))
  5709. def on_qrcode_back_color_button(self):
  5710. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  5711. c_dialog = QtWidgets.QColorDialog()
  5712. back_color = c_dialog.getColor(initial=current_color)
  5713. if back_color.isValid() is False:
  5714. return
  5715. # if new color is different then mark that the Preferences are changed
  5716. if back_color != current_color:
  5717. self.on_preferences_edited()
  5718. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5719. "background-color:%s" % str(back_color.name()))
  5720. new_val_sel = str(back_color.name())
  5721. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  5722. self.defaults['tools_qrcode_back_color'] = new_val_sel
  5723. def on_splash_changed(self, state):
  5724. settings = QSettings("Open Source", "FlatCAM")
  5725. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  5726. # This will write the setting to the platform specific storage.
  5727. del settings
  5728. def on_tab_rmb_click(self, checked):
  5729. self.ui.notebook.set_detachable(val=checked)
  5730. self.defaults["global_tabs_detachable"] = checked
  5731. self.ui.plot_tab_area.set_detachable(val=checked)
  5732. self.defaults["global_tabs_detachable"] = checked
  5733. def on_tab_setup_context_menu(self):
  5734. initial_checked = self.defaults["global_tabs_detachable"]
  5735. action_name = str(_("Detachable Tabs"))
  5736. action = QtWidgets.QAction(self)
  5737. action.setCheckable(True)
  5738. action.setText(action_name)
  5739. action.setChecked(initial_checked)
  5740. self.ui.notebook.tabBar.addAction(action)
  5741. self.ui.plot_tab_area.tabBar.addAction(action)
  5742. try:
  5743. action.triggered.disconnect()
  5744. except TypeError:
  5745. pass
  5746. action.triggered.connect(self.on_tab_rmb_click)
  5747. def on_deselect_all(self):
  5748. self.collection.set_all_inactive()
  5749. self.delete_selection_shape()
  5750. def on_workspace_modified(self):
  5751. self.save_defaults(silent=True)
  5752. self.plotcanvas.draw_workspace()
  5753. def on_workspace(self):
  5754. self.report_usage("on_workspace()")
  5755. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5756. self.plotcanvas.restore_workspace()
  5757. else:
  5758. self.plotcanvas.delete_workspace()
  5759. self.save_defaults(silent=True)
  5760. def on_workspace_menu(self):
  5761. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5762. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  5763. else:
  5764. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  5765. self.on_workspace()
  5766. def on_layout(self, index=None, lay=None):
  5767. """
  5768. Set the toolbars layout (location)
  5769. :param index:
  5770. :param lay: type of layout to be set on the toolbard
  5771. :return: None
  5772. """
  5773. self.report_usage("on_layout()")
  5774. if lay:
  5775. current_layout = lay
  5776. else:
  5777. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  5778. settings = QSettings("Open Source", "FlatCAM")
  5779. settings.setValue('layout', current_layout)
  5780. # This will write the setting to the platform specific storage.
  5781. del settings
  5782. # first remove the toolbars:
  5783. try:
  5784. self.ui.removeToolBar(self.ui.toolbarfile)
  5785. self.ui.removeToolBar(self.ui.toolbargeo)
  5786. self.ui.removeToolBar(self.ui.toolbarview)
  5787. self.ui.removeToolBar(self.ui.toolbarshell)
  5788. self.ui.removeToolBar(self.ui.toolbartools)
  5789. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  5790. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  5791. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  5792. self.ui.removeToolBar(self.ui.snap_toolbar)
  5793. self.ui.removeToolBar(self.ui.toolbarshell)
  5794. except Exception as e:
  5795. pass
  5796. if current_layout == 'standard':
  5797. # ## TOOLBAR INSTALLATION # ##
  5798. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5799. self.ui.toolbarfile.setObjectName('File_TB')
  5800. self.ui.addToolBar(self.ui.toolbarfile)
  5801. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5802. self.ui.toolbargeo.setObjectName('Edit_TB')
  5803. self.ui.addToolBar(self.ui.toolbargeo)
  5804. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5805. self.ui.toolbarview.setObjectName('View_TB')
  5806. self.ui.addToolBar(self.ui.toolbarview)
  5807. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5808. self.ui.toolbarshell.setObjectName('Shell_TB')
  5809. self.ui.addToolBar(self.ui.toolbarshell)
  5810. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5811. self.ui.toolbartools.setObjectName('Tools_TB')
  5812. self.ui.addToolBar(self.ui.toolbartools)
  5813. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5814. # self.ui.exc_edit_toolbar.setVisible(False)
  5815. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5816. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  5817. self.ui.addToolBarBreak()
  5818. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5819. # self.ui.geo_edit_toolbar.setVisible(False)
  5820. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5821. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  5822. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5823. # self.ui.grb_edit_toolbar.setVisible(False)
  5824. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5825. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  5826. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5827. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5828. # self.ui.snap_toolbar.setMaximumHeight(30)
  5829. self.ui.addToolBar(self.ui.snap_toolbar)
  5830. self.ui.corner_snap_btn.setVisible(False)
  5831. self.ui.snap_magnet.setVisible(False)
  5832. elif current_layout == 'compact':
  5833. # ## TOOLBAR INSTALLATION # ##
  5834. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5835. self.ui.toolbarfile.setObjectName('File_TB')
  5836. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  5837. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5838. self.ui.toolbargeo.setObjectName('Edit_TB')
  5839. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  5840. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5841. self.ui.toolbarshell.setObjectName('Shell_TB')
  5842. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  5843. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5844. self.ui.toolbartools.setObjectName('Tools_TB')
  5845. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  5846. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5847. # self.ui.geo_edit_toolbar.setVisible(False)
  5848. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5849. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  5850. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5851. self.ui.toolbarview.setObjectName('View_TB')
  5852. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  5853. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  5854. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5855. # self.ui.grb_edit_toolbar.setVisible(False)
  5856. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5857. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  5858. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5859. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5860. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  5861. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5862. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5863. self.ui.snap_toolbar.setMaximumHeight(30)
  5864. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  5865. self.ui.corner_snap_btn.setVisible(True)
  5866. self.ui.snap_magnet.setVisible(True)
  5867. # add all the actions to the toolbars
  5868. self.ui.populate_toolbars()
  5869. # reconnect all the signals to the toolbar actions
  5870. self.connect_toolbar_signals()
  5871. self.ui.grid_snap_btn.setChecked(True)
  5872. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  5873. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  5874. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  5875. self.ui.grid_gap_link_cb.setChecked(True)
  5876. def on_cursor_type(self, val):
  5877. """
  5878. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  5879. :return: None
  5880. """
  5881. self.app_cursor.enabled = False
  5882. if val == 'small':
  5883. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(False)
  5884. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(False)
  5885. self.app_cursor = self.plotcanvas.new_cursor()
  5886. else:
  5887. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(True)
  5888. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(True)
  5889. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  5890. if self.ui.grid_snap_btn.isChecked():
  5891. self.app_cursor.enabled = True
  5892. else:
  5893. self.app_cursor.enabled = False
  5894. def on_cnc_custom_parameters(self, signal_text):
  5895. if signal_text == 'Parameters':
  5896. return
  5897. else:
  5898. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5899. def on_save_button(self):
  5900. log.debug("App.on_save_button() --> Saving preferences to file.")
  5901. self.preferences_changed_flag = False
  5902. self.save_defaults(silent=False)
  5903. # load the defaults so they are updated into the app
  5904. self.load_defaults(filename='current_defaults')
  5905. # Re-fresh project options
  5906. self.on_options_app2project()
  5907. settings = QSettings("Open Source", "FlatCAM")
  5908. # save the notebook font size
  5909. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  5910. settings.setValue('notebook_font_size', fsize)
  5911. # save the axis font size
  5912. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  5913. settings.setValue('axis_font_size', g_fsize)
  5914. # save the textbox font size
  5915. tb_fsize = self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  5916. settings.setValue('textbox_font_size', tb_fsize)
  5917. # This will write the setting to the platform specific storage.
  5918. del settings
  5919. def on_tool_add_keypress(self):
  5920. # ## Current application units in Upper Case
  5921. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5922. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5923. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5924. if notebook_widget_name == 'selected_tab':
  5925. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5926. # Tool add works for Geometry only if Advanced is True in Preferences
  5927. if self.defaults["global_app_level"] == 'a':
  5928. tool_add_popup = FCInputDialog(title="New Tool ...",
  5929. text='Enter a Tool Diameter:',
  5930. min=0.0000, max=99.9999, decimals=4)
  5931. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5932. val, ok = tool_add_popup.get_value()
  5933. if ok:
  5934. if float(val) == 0:
  5935. self.inform.emit('[WARNING_NOTCL] %s' %
  5936. _("Please enter a tool diameter with non-zero value, in Float format."))
  5937. return
  5938. self.collection.get_active().on_tool_add(dia=float(val))
  5939. else:
  5940. self.inform.emit('[WARNING_NOTCL] %s...' %
  5941. _("Adding Tool cancelled"))
  5942. else:
  5943. msgbox = QtWidgets.QMessageBox()
  5944. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5945. "Go to Preferences -> General - Show Advanced Options."))
  5946. msgbox.setWindowTitle("Tool adding ...")
  5947. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  5948. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5949. msgbox.setDefaultButton(bt_ok)
  5950. msgbox.exec_()
  5951. # work only if the notebook tab on focus is the Tools_Tab
  5952. if notebook_widget_name == 'tool_tab':
  5953. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5954. # and only if the tool is NCC Tool
  5955. if tool_widget == self.ncclear_tool.toolName:
  5956. self.ncclear_tool.on_add_tool_by_key()
  5957. # and only if the tool is Paint Area Tool
  5958. elif tool_widget == self.paint_tool.toolName:
  5959. self.paint_tool.on_add_tool_by_key()
  5960. # and only if the tool is Solder Paste Dispensing Tool
  5961. elif tool_widget == self.paste_tool.toolName:
  5962. self.paste_tool.on_add_tool_by_key()
  5963. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5964. # See description bellow.
  5965. def on_delete_keypress(self):
  5966. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5967. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5968. if notebook_widget_name == 'selected_tab':
  5969. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5970. self.collection.get_active().on_tool_delete()
  5971. # work only if the notebook tab on focus is the Tools_Tab
  5972. elif notebook_widget_name == 'tool_tab':
  5973. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5974. # and only if the tool is NCC Tool
  5975. if tool_widget == self.ncclear_tool.toolName:
  5976. self.ncclear_tool.on_tool_delete()
  5977. # and only if the tool is Paint Tool
  5978. elif tool_widget == self.paint_tool.toolName:
  5979. self.paint_tool.on_tool_delete()
  5980. # and only if the tool is Solder Paste Dispensing Tool
  5981. elif tool_widget == self.paste_tool.toolName:
  5982. self.paste_tool.on_tool_delete()
  5983. else:
  5984. self.on_delete()
  5985. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5986. # some screens you have to be careful where you hover with your mouse.
  5987. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5988. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5989. # Complicated, I know :)
  5990. def on_delete(self):
  5991. """
  5992. Delete the currently selected FlatCAMObjs.
  5993. :return: None
  5994. """
  5995. self.report_usage("on_delete()")
  5996. response = None
  5997. bt_ok = None
  5998. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5999. # a geometry object before we update it.
  6000. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  6001. and self.grb_editor.editor_active is False:
  6002. if self.defaults["global_delete_confirmation"] is True:
  6003. msgbox = QtWidgets.QMessageBox()
  6004. msgbox.setWindowTitle(_("Delete objects"))
  6005. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  6006. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  6007. msgbox.setText(_("Are you sure you want to permanently delete\n"
  6008. "the selected objects?"))
  6009. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6010. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6011. msgbox.setDefaultButton(bt_ok)
  6012. msgbox.exec_()
  6013. response = msgbox.clickedButton()
  6014. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  6015. if self.collection.get_active():
  6016. self.log.debug("App.on_delete()")
  6017. while self.collection.get_active():
  6018. obj_active = self.collection.get_active()
  6019. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  6020. if isinstance(obj_active, FlatCAMGerber):
  6021. for el in obj_active.mark_shapes:
  6022. obj_active.mark_shapes[el].clear(update=True)
  6023. obj_active.mark_shapes[el].enabled = False
  6024. # obj_active.mark_shapes[el] = None
  6025. del el
  6026. elif isinstance(obj_active, FlatCAMCNCjob):
  6027. try:
  6028. obj_active.annotation.clear(update=True)
  6029. obj_active.annotation.enabled = False
  6030. except AttributeError:
  6031. pass
  6032. self.delete_first_selected()
  6033. self.inform.emit('%s...' %
  6034. _("Object(s) deleted"))
  6035. # make sure that the selection shape is deleted, too
  6036. self.delete_selection_shape()
  6037. else:
  6038. self.inform.emit(_("Failed. No object(s) selected..."))
  6039. else:
  6040. self.inform.emit(_("Save the work in Editor and try again ..."))
  6041. def delete_first_selected(self):
  6042. # Keep this for later
  6043. try:
  6044. sel_obj = self.collection.get_active()
  6045. name = sel_obj.options["name"]
  6046. isPlotted = sel_obj.options["plot"]
  6047. except AttributeError:
  6048. self.log.debug("Nothing selected for deletion")
  6049. return
  6050. if self.is_legacy is True:
  6051. # Remove plot only if the object was plotted otherwise delaxes will fail
  6052. if isPlotted:
  6053. try:
  6054. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  6055. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  6056. except Exception as e:
  6057. log.debug("App.delete_first_selected() --> %s" % str(e))
  6058. self.plotcanvas.auto_adjust_axes()
  6059. # Remove from dictionary
  6060. self.collection.delete_active()
  6061. # Clear form
  6062. self.setup_component_editor()
  6063. self.inform.emit('%s: %s' %
  6064. (_("Object deleted"), name))
  6065. def on_set_origin(self):
  6066. """
  6067. Set the origin to the left mouse click position
  6068. :return: None
  6069. """
  6070. # display the message for the user
  6071. # and ask him to click on the desired position
  6072. self.report_usage("on_set_origin()")
  6073. def origin_replot():
  6074. def worker_task():
  6075. with self.proc_container.new('%s...' % _("Plotting")):
  6076. for obj in self.collection.get_list():
  6077. obj.plot()
  6078. self.plotcanvas.fit_view()
  6079. if self.is_legacy:
  6080. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  6081. else:
  6082. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  6083. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6084. self.inform.emit(_('Click to set the origin ...'))
  6085. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  6086. # first disconnect it as it may have been used by something else
  6087. try:
  6088. self.replot_signal.disconnect()
  6089. except TypeError:
  6090. pass
  6091. self.replot_signal[list].connect(origin_replot)
  6092. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  6093. """
  6094. :param event:
  6095. :param location:
  6096. :param noplot:
  6097. :param use_thread:
  6098. :return:
  6099. """
  6100. noplot_sig = noplot
  6101. def worker_task():
  6102. with self.proc_container.new(_("Setting Origin...")):
  6103. for obj in self.collection.get_list():
  6104. obj.offset((x, y))
  6105. self.object_changed.emit(obj)
  6106. # Update the object bounding box options
  6107. a, b, c, d = obj.bounds()
  6108. obj.options['xmin'] = a
  6109. obj.options['ymin'] = b
  6110. obj.options['xmax'] = c
  6111. obj.options['ymax'] = d
  6112. self.inform.emit('[success] %s...' %
  6113. _('Origin set'))
  6114. if noplot_sig is False:
  6115. self.replot_signal.emit([])
  6116. if location is not None:
  6117. if len(location) != 2:
  6118. self.inform.emit('[ERROR_NOTCL] %s...' %
  6119. _("Origin coordinates specified but incomplete."))
  6120. return 'fail'
  6121. x, y = location
  6122. if use_thread is True:
  6123. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6124. else:
  6125. worker_task()
  6126. self.should_we_save = True
  6127. return
  6128. if event.button == 1:
  6129. if self.is_legacy is False:
  6130. event_pos = event.pos
  6131. else:
  6132. event_pos = (event.xdata, event.ydata)
  6133. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6134. if self.grid_status() == True:
  6135. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6136. else:
  6137. pos = pos_canvas
  6138. x = 0 - pos[0]
  6139. y = 0 - pos[1]
  6140. if use_thread is True:
  6141. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6142. else:
  6143. worker_task()
  6144. self.should_we_save = True
  6145. def on_jump_to(self, custom_location=None, fit_center=True):
  6146. """
  6147. Jump to a location by setting the mouse cursor location
  6148. :return:
  6149. """
  6150. self.report_usage("on_jump_to()")
  6151. # if self.is_legacy is True:
  6152. # self.inform.emit(_("Not available with the current Graphic Engine Legacy(2D)."))
  6153. # return
  6154. if not custom_location:
  6155. dia_box_location = None
  6156. try:
  6157. dia_box_location = eval(self.clipboard.text())
  6158. except Exception as e:
  6159. pass
  6160. if type(dia_box_location) == tuple:
  6161. dia_box_location = str(dia_box_location)
  6162. else:
  6163. dia_box_location = None
  6164. dia_box = Dialog_box(title=_("Jump to ..."),
  6165. label=_("Enter the coordinates in format X,Y:"),
  6166. icon=QtGui.QIcon('share/jump_to16.png'),
  6167. initial_text=dia_box_location)
  6168. if dia_box.ok is True:
  6169. try:
  6170. location = eval(dia_box.location)
  6171. if not isinstance(location, tuple):
  6172. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  6173. return
  6174. except:
  6175. return
  6176. else:
  6177. return
  6178. else:
  6179. location = custom_location
  6180. if fit_center:
  6181. self.plotcanvas.fit_center(loc=location)
  6182. cursor = QtGui.QCursor()
  6183. if self.is_legacy is False:
  6184. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6185. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  6186. j_pos = (canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  6187. cursor.setPos(j_pos[0], j_pos[1])
  6188. else:
  6189. # find the canvas origin which is in the top left corner
  6190. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6191. # determine the coordinates for the lowest left point of the canvas
  6192. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  6193. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  6194. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  6195. # canvas) and the point (width, height) is in the top-right location
  6196. loc = self.plotcanvas.axes.transData.transform_point(location)
  6197. j_pos = (x0 + loc[0], y0 - loc[1])
  6198. cursor.setPos(j_pos[0], j_pos[1])
  6199. if self.grid_status() == True:
  6200. # Update cursor
  6201. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  6202. symbol='++', edge_color=self.cursor_color_3D,
  6203. size=self.defaults["global_cursor_size"])
  6204. # Set the position label
  6205. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6206. "<b>Y</b>: %.4f" % (location[0], location[1]))
  6207. # Set the relative position label
  6208. dx = location[0] - float(self.rel_point1[0])
  6209. dy = location[1] - float(self.rel_point1[1])
  6210. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6211. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6212. self.inform.emit('[success] %s' %
  6213. _("Done."))
  6214. return location
  6215. def on_copy_object(self):
  6216. self.report_usage("on_copy_object()")
  6217. def initialize(obj_init, app):
  6218. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6219. try:
  6220. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  6221. except AttributeError:
  6222. pass
  6223. try:
  6224. obj_init.apertures = deepcopy(obj.apertures)
  6225. except AttributeError:
  6226. pass
  6227. try:
  6228. if obj.tools:
  6229. obj_init.tools = deepcopy(obj.tools)
  6230. except Exception as e:
  6231. log.debug("App.on_copy_object() --> %s" % str(e))
  6232. def initialize_excellon(obj_init, app):
  6233. obj_init.tools = deepcopy(obj.tools)
  6234. # drills are offset, so they need to be deep copied
  6235. obj_init.drills = deepcopy(obj.drills)
  6236. # slots are offset, so they need to be deep copied
  6237. obj_init.slots = deepcopy(obj.slots)
  6238. obj_init.create_geometry()
  6239. def initialize_script(obj_init, app_obj):
  6240. obj_init.source_file = deepcopy(obj.source_file)
  6241. def initialize_document(obj_init, app_obj):
  6242. obj_init.source_file = deepcopy(obj.source_file)
  6243. for obj in self.collection.get_selected():
  6244. obj_name = obj.options["name"]
  6245. try:
  6246. if isinstance(obj, FlatCAMExcellon):
  6247. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  6248. elif isinstance(obj, FlatCAMGerber):
  6249. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  6250. elif isinstance(obj, FlatCAMGeometry):
  6251. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  6252. elif isinstance(obj, FlatCAMScript):
  6253. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  6254. elif isinstance(obj, FlatCAMDocument):
  6255. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  6256. except Exception as e:
  6257. return "Operation failed: %s" % str(e)
  6258. def on_copy_object2(self, custom_name):
  6259. def initialize_geometry(obj_init, app):
  6260. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6261. try:
  6262. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  6263. except AttributeError:
  6264. pass
  6265. try:
  6266. obj_init.apertures = deepcopy(obj.apertures)
  6267. except AttributeError:
  6268. pass
  6269. try:
  6270. if obj.tools:
  6271. obj_init.tools = deepcopy(obj.tools)
  6272. except Exception as e:
  6273. log.debug("on_copy_object2() --> %s" % str(e))
  6274. def initialize_gerber(obj_init, app):
  6275. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6276. obj_init.apertures = deepcopy(obj.apertures)
  6277. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  6278. def initialize_excellon(obj_init, app):
  6279. obj_init.tools = deepcopy(obj.tools)
  6280. # drills are offset, so they need to be deep copied
  6281. obj_init.drills = deepcopy(obj.drills)
  6282. # slots are offset, so they need to be deep copied
  6283. obj_init.slots = deepcopy(obj.slots)
  6284. obj_init.create_geometry()
  6285. for obj in self.collection.get_selected():
  6286. obj_name = obj.options["name"]
  6287. try:
  6288. if isinstance(obj, FlatCAMExcellon):
  6289. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  6290. elif isinstance(obj, FlatCAMGerber):
  6291. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  6292. elif isinstance(obj, FlatCAMGeometry):
  6293. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  6294. except Exception as e:
  6295. return "Operation failed: %s" % str(e)
  6296. def on_rename_object(self, text):
  6297. self.report_usage("on_rename_object()")
  6298. named_obj = self.collection.get_active()
  6299. for obj in named_obj:
  6300. if obj is list:
  6301. self.on_rename_object(text)
  6302. else:
  6303. try:
  6304. obj.options['name'] = text
  6305. except Exception as e:
  6306. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  6307. def convert_any2geo(self):
  6308. self.report_usage("convert_any2geo()")
  6309. def initialize(obj_init, app):
  6310. obj_init.solid_geometry = obj.solid_geometry
  6311. try:
  6312. obj_init.follow_geometry = obj.follow_geometry
  6313. except AttributeError:
  6314. pass
  6315. try:
  6316. obj_init.apertures = obj.apertures
  6317. except AttributeError:
  6318. pass
  6319. try:
  6320. if obj.tools:
  6321. obj_init.tools = obj.tools
  6322. except AttributeError:
  6323. pass
  6324. def initialize_excellon(obj_init, app):
  6325. # objs = self.collection.get_selected()
  6326. # FlatCAMGeometry.merge(objs, obj)
  6327. solid_geo = []
  6328. for tool in obj.tools:
  6329. for geo in obj.tools[tool]['solid_geometry']:
  6330. solid_geo.append(geo)
  6331. obj_init.solid_geometry = deepcopy(solid_geo)
  6332. if not self.collection.get_selected():
  6333. log.warning("App.convert_any2geo --> No object selected")
  6334. self.inform.emit('[WARNING_NOTCL] %s' %
  6335. _("No object is selected. Select an object and try again."))
  6336. return
  6337. for obj in self.collection.get_selected():
  6338. obj_name = obj.options["name"]
  6339. try:
  6340. if isinstance(obj, FlatCAMExcellon):
  6341. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  6342. else:
  6343. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  6344. except Exception as e:
  6345. return "Operation failed: %s" % str(e)
  6346. def convert_any2gerber(self):
  6347. self.report_usage("convert_any2gerber()")
  6348. def initialize_geometry(obj_init, app):
  6349. apertures = {}
  6350. apid = 0
  6351. apertures[str(apid)] = {}
  6352. apertures[str(apid)]['geometry'] = []
  6353. for obj_orig in obj.solid_geometry:
  6354. new_elem = dict()
  6355. new_elem['solid'] = obj_orig
  6356. try:
  6357. new_elem['follow'] = obj_orig.exterior
  6358. except AttributeError:
  6359. pass
  6360. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  6361. apertures[str(apid)]['size'] = 0.0
  6362. apertures[str(apid)]['type'] = 'C'
  6363. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6364. obj_init.apertures = deepcopy(apertures)
  6365. def initialize_excellon(obj_init, app):
  6366. apertures = {}
  6367. apid = 10
  6368. for tool in obj.tools:
  6369. apertures[str(apid)] = {}
  6370. apertures[str(apid)]['geometry'] = []
  6371. for geo in obj.tools[tool]['solid_geometry']:
  6372. new_el = dict()
  6373. new_el['solid'] = geo
  6374. new_el['follow'] = geo.exterior
  6375. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  6376. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  6377. apertures[str(apid)]['type'] = 'C'
  6378. apid += 1
  6379. # create solid_geometry
  6380. solid_geometry = []
  6381. for apid in apertures:
  6382. for geo_el in apertures[apid]['geometry']:
  6383. solid_geometry.append(geo_el['solid'])
  6384. solid_geometry = MultiPolygon(solid_geometry)
  6385. solid_geometry = solid_geometry.buffer(0.0000001)
  6386. obj_init.solid_geometry = deepcopy(solid_geometry)
  6387. obj_init.apertures = deepcopy(apertures)
  6388. # clear the working objects (perhaps not necessary due of Python GC)
  6389. apertures.clear()
  6390. if not self.collection.get_selected():
  6391. log.warning("App.convert_any2gerber --> No object selected")
  6392. self.inform.emit('[WARNING_NOTCL] %s' %
  6393. _("No object is selected. Select an object and try again."))
  6394. return
  6395. for obj in self.collection.get_selected():
  6396. obj_name = obj.options["name"]
  6397. try:
  6398. if isinstance(obj, FlatCAMExcellon):
  6399. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  6400. elif isinstance(obj, FlatCAMGeometry):
  6401. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  6402. else:
  6403. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  6404. except Exception as e:
  6405. return "Operation failed: %s" % str(e)
  6406. def abort_all_tasks(self):
  6407. if self.abort_flag is False:
  6408. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  6409. self.abort_flag = True
  6410. def app_is_idle(self):
  6411. if self.abort_flag:
  6412. self.inform.emit('[WARNING_NOTCL] %s' %
  6413. _("The current task was gracefully closed on user request..."))
  6414. self.abort_flag = False
  6415. def on_selectall(self):
  6416. self.report_usage("on_selectall()")
  6417. # delete the possible selection box around a possible selected object
  6418. self.delete_selection_shape()
  6419. for name in self.collection.get_names():
  6420. self.collection.set_active(name)
  6421. curr_sel_obj = self.collection.get_by_name(name)
  6422. # create the selection box around the selected object
  6423. if self.defaults['global_selection_shape'] is True:
  6424. self.draw_selection_shape(curr_sel_obj)
  6425. def on_preferences(self):
  6426. # add the tab if it was closed
  6427. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  6428. # delete the absolute and relative position and messages in the infobar
  6429. self.ui.position_label.setText("")
  6430. self.ui.rel_position_label.setText("")
  6431. # Switch plot_area to preferences page
  6432. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  6433. # self.ui.show()
  6434. # detect changes in the preferences
  6435. for idx in range(self.ui.pref_tab_area.count()):
  6436. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6437. try:
  6438. try:
  6439. tb.textEdited.disconnect(self.on_preferences_edited)
  6440. except (TypeError, AttributeError):
  6441. pass
  6442. tb.textEdited.connect(self.on_preferences_edited)
  6443. except AttributeError:
  6444. pass
  6445. try:
  6446. try:
  6447. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6448. except (TypeError, AttributeError):
  6449. pass
  6450. tb.modificationChanged.connect(self.on_preferences_edited)
  6451. except AttributeError:
  6452. pass
  6453. try:
  6454. try:
  6455. tb.toggled.disconnect(self.on_preferences_edited)
  6456. except (TypeError, AttributeError):
  6457. pass
  6458. tb.toggled.connect(self.on_preferences_edited)
  6459. except AttributeError:
  6460. pass
  6461. try:
  6462. try:
  6463. tb.valueChanged.disconnect(self.on_preferences_edited)
  6464. except (TypeError, AttributeError):
  6465. pass
  6466. tb.valueChanged.connect(self.on_preferences_edited)
  6467. except AttributeError:
  6468. pass
  6469. try:
  6470. try:
  6471. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6472. except (TypeError, AttributeError):
  6473. pass
  6474. tb.currentIndexChanged.connect(self.on_preferences_edited)
  6475. except AttributeError:
  6476. pass
  6477. def on_preferences_edited(self):
  6478. self.inform.emit('[WARNING_NOTCL] %s' %
  6479. _("Preferences edited but not saved."))
  6480. self.preferences_changed_flag = True
  6481. def on_plot_area_tab_closed(self, title):
  6482. if title == _("Preferences"):
  6483. # disconnect
  6484. for idx in range(self.ui.pref_tab_area.count()):
  6485. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6486. try:
  6487. tb.textEdited.disconnect(self.on_preferences_edited)
  6488. except (TypeError, AttributeError):
  6489. pass
  6490. try:
  6491. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6492. except (TypeError, AttributeError):
  6493. pass
  6494. try:
  6495. tb.toggled.disconnect(self.on_preferences_edited)
  6496. except (TypeError, AttributeError):
  6497. pass
  6498. try:
  6499. tb.valueChanged.disconnect(self.on_preferences_edited)
  6500. except (TypeError, AttributeError):
  6501. pass
  6502. try:
  6503. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6504. except (TypeError, AttributeError):
  6505. pass
  6506. if self.preferences_changed_flag is True:
  6507. msgbox = QtWidgets.QMessageBox()
  6508. msgbox.setText(_("One or more values are changed.\n"
  6509. "Do you want to save the Preferences?"))
  6510. msgbox.setWindowTitle(_("Save Preferences"))
  6511. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6512. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6513. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6514. msgbox.setDefaultButton(bt_yes)
  6515. msgbox.exec_()
  6516. response = msgbox.clickedButton()
  6517. if response == bt_yes:
  6518. self.on_save_button()
  6519. self.inform.emit('[success] %s' %
  6520. _("Preferences saved."))
  6521. else:
  6522. self.preferences_changed_flag = False
  6523. return
  6524. if title == _("Code Editor"):
  6525. self.toggle_codeeditor = False
  6526. if title == _("Bookmarks Manager"):
  6527. self.book_dialog_tab.rebuild_actions()
  6528. self.book_dialog_tab.deleteLater()
  6529. def on_flipy(self):
  6530. self.report_usage("on_flipy()")
  6531. obj_list = self.collection.get_selected()
  6532. xminlist = []
  6533. yminlist = []
  6534. xmaxlist = []
  6535. ymaxlist = []
  6536. if not obj_list:
  6537. self.inform.emit('[WARNING_NOTCL] %s' %
  6538. _("No object selected to Flip on Y axis."))
  6539. else:
  6540. try:
  6541. # first get a bounding box to fit all
  6542. for obj in obj_list:
  6543. xmin, ymin, xmax, ymax = obj.bounds()
  6544. xminlist.append(xmin)
  6545. yminlist.append(ymin)
  6546. xmaxlist.append(xmax)
  6547. ymaxlist.append(ymax)
  6548. # get the minimum x,y and maximum x,y for all objects selected
  6549. xminimal = min(xminlist)
  6550. yminimal = min(yminlist)
  6551. xmaximal = max(xmaxlist)
  6552. ymaximal = max(ymaxlist)
  6553. px = 0.5 * (xminimal + xmaximal)
  6554. py = 0.5 * (yminimal + ymaximal)
  6555. # execute mirroring
  6556. for obj in obj_list:
  6557. obj.mirror('X', [px, py])
  6558. obj.plot()
  6559. self.object_changed.emit(obj)
  6560. self.inform.emit('[success] %s' %
  6561. _("Flip on Y axis done."))
  6562. except Exception as e:
  6563. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6564. (_("Flip action was not executed."), str(e)))
  6565. return
  6566. def on_flipx(self):
  6567. self.report_usage("on_flipx()")
  6568. obj_list = self.collection.get_selected()
  6569. xminlist = []
  6570. yminlist = []
  6571. xmaxlist = []
  6572. ymaxlist = []
  6573. if not obj_list:
  6574. self.inform.emit('[WARNING_NOTCL] %s' %
  6575. _("No object selected to Flip on X axis."))
  6576. else:
  6577. try:
  6578. # first get a bounding box to fit all
  6579. for obj in obj_list:
  6580. xmin, ymin, xmax, ymax = obj.bounds()
  6581. xminlist.append(xmin)
  6582. yminlist.append(ymin)
  6583. xmaxlist.append(xmax)
  6584. ymaxlist.append(ymax)
  6585. # get the minimum x,y and maximum x,y for all objects selected
  6586. xminimal = min(xminlist)
  6587. yminimal = min(yminlist)
  6588. xmaximal = max(xmaxlist)
  6589. ymaximal = max(ymaxlist)
  6590. px = 0.5 * (xminimal + xmaximal)
  6591. py = 0.5 * (yminimal + ymaximal)
  6592. # execute mirroring
  6593. for obj in obj_list:
  6594. obj.mirror('Y', [px, py])
  6595. obj.plot()
  6596. self.object_changed.emit(obj)
  6597. self.inform.emit('[success] %s' %
  6598. _("Flip on X axis done."))
  6599. except Exception as e:
  6600. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6601. (_("Flip action was not executed."), str(e)))
  6602. return
  6603. def on_rotate(self, silent=False, preset=None):
  6604. self.report_usage("on_rotate()")
  6605. obj_list = self.collection.get_selected()
  6606. xminlist = []
  6607. yminlist = []
  6608. xmaxlist = []
  6609. ymaxlist = []
  6610. if not obj_list:
  6611. self.inform.emit('[WARNING_NOTCL] %s' %
  6612. _("No object selected to Rotate."))
  6613. else:
  6614. if silent is False:
  6615. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6616. min=-360, max=360, decimals=4,
  6617. init_val=float(self.defaults['tools_transform_rotate']))
  6618. num, ok = rotatebox.get_value()
  6619. else:
  6620. num = preset
  6621. ok = True
  6622. if ok:
  6623. try:
  6624. # first get a bounding box to fit all
  6625. for obj in obj_list:
  6626. xmin, ymin, xmax, ymax = obj.bounds()
  6627. xminlist.append(xmin)
  6628. yminlist.append(ymin)
  6629. xmaxlist.append(xmax)
  6630. ymaxlist.append(ymax)
  6631. # get the minimum x,y and maximum x,y for all objects selected
  6632. xminimal = min(xminlist)
  6633. yminimal = min(yminlist)
  6634. xmaximal = max(xmaxlist)
  6635. ymaximal = max(ymaxlist)
  6636. px = 0.5 * (xminimal + xmaximal)
  6637. py = 0.5 * (yminimal + ymaximal)
  6638. for sel_obj in obj_list:
  6639. sel_obj.rotate(-float(num), point=(px, py))
  6640. sel_obj.plot()
  6641. self.object_changed.emit(sel_obj)
  6642. self.inform.emit('[success] %s' %
  6643. _("Rotation done."))
  6644. except Exception as e:
  6645. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6646. (_("Rotation movement was not executed."), str(e)))
  6647. return
  6648. def on_skewx(self):
  6649. self.report_usage("on_skewx()")
  6650. obj_list = self.collection.get_selected()
  6651. xminlist = []
  6652. yminlist = []
  6653. if not obj_list:
  6654. self.inform.emit('[WARNING_NOTCL] %s' %
  6655. _("No object selected to Skew/Shear on X axis."))
  6656. else:
  6657. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6658. min=-360, max=360, decimals=4,
  6659. init_val=float(self.defaults['tools_transform_skew_x']))
  6660. num, ok = skewxbox.get_value()
  6661. if ok:
  6662. # first get a bounding box to fit all
  6663. for obj in obj_list:
  6664. xmin, ymin, xmax, ymax = obj.bounds()
  6665. xminlist.append(xmin)
  6666. yminlist.append(ymin)
  6667. # get the minimum x,y and maximum x,y for all objects selected
  6668. xminimal = min(xminlist)
  6669. yminimal = min(yminlist)
  6670. for obj in obj_list:
  6671. obj.skew(num, 0, point=(xminimal, yminimal))
  6672. obj.plot()
  6673. self.object_changed.emit(obj)
  6674. self.inform.emit('[success] %s' %
  6675. _("Skew on X axis done."))
  6676. def on_skewy(self):
  6677. self.report_usage("on_skewy()")
  6678. obj_list = self.collection.get_selected()
  6679. xminlist = []
  6680. yminlist = []
  6681. if not obj_list:
  6682. self.inform.emit('[WARNING_NOTCL] %s' %
  6683. _("No object selected to Skew/Shear on Y axis."))
  6684. else:
  6685. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6686. min=-360, max=360, decimals=4,
  6687. init_val=float(self.defaults['tools_transform_skew_y']))
  6688. num, ok = skewybox.get_value()
  6689. if ok:
  6690. # first get a bounding box to fit all
  6691. for obj in obj_list:
  6692. xmin, ymin, xmax, ymax = obj.bounds()
  6693. xminlist.append(xmin)
  6694. yminlist.append(ymin)
  6695. # get the minimum x,y and maximum x,y for all objects selected
  6696. xminimal = min(xminlist)
  6697. yminimal = min(yminlist)
  6698. for obj in obj_list:
  6699. obj.skew(0, num, point=(xminimal, yminimal))
  6700. obj.plot()
  6701. self.object_changed.emit(obj)
  6702. self.inform.emit('[success] %s' %
  6703. _("Skew on Y axis done."))
  6704. def on_plots_updated(self):
  6705. """
  6706. Callback used to report when the plots have changed.
  6707. Adjust axes and zooms to fit.
  6708. :return: None
  6709. """
  6710. if self.is_legacy is False:
  6711. self.plotcanvas.update() # TODO: Need update canvas?
  6712. else:
  6713. self.plotcanvas.auto_adjust_axes()
  6714. self.on_zoom_fit(None)
  6715. self.collection.update_view()
  6716. # self.inform.emit(_("Plots updated ..."))
  6717. # TODO: Rework toolbar 'clear', 'replot' functions
  6718. def on_toolbar_replot(self):
  6719. """
  6720. Callback for toolbar button. Re-plots all objects.
  6721. :return: None
  6722. """
  6723. self.report_usage("on_toolbar_replot")
  6724. self.log.debug("on_toolbar_replot()")
  6725. try:
  6726. self.collection.get_active().read_form()
  6727. except AttributeError:
  6728. self.log.debug("on_toolbar_replot(): AttributeError")
  6729. pass
  6730. self.plot_all()
  6731. def on_row_activated(self, index):
  6732. if index.isValid():
  6733. if index.internalPointer().parent_item != self.collection.root_item:
  6734. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6735. self.collection.on_item_activated(index)
  6736. def on_row_selected(self, obj_name):
  6737. # this is a special string; when received it will make all entries unchecked
  6738. # it mean we clicked outside of the items and deselected all
  6739. if obj_name =='none':
  6740. for act in self.ui.menuobjects.actions():
  6741. act.setChecked(False)
  6742. return
  6743. # get the name of the selected objects and add them to a list
  6744. name_list = list()
  6745. for obj in self.collection.get_selected():
  6746. name_list.append(obj.options['name'])
  6747. # set all actions as unchecked but the ones selected make them checked
  6748. for act in self.ui.menuobjects.actions():
  6749. act.setChecked(False)
  6750. if act.text() in name_list:
  6751. act.setChecked(True)
  6752. def on_collection_updated(self, obj, state, old_name):
  6753. """
  6754. Create a menu from the object loaded in the collection.
  6755. TODO: should use the collection model to do this
  6756. :param obj: object that was changd (added, deleted, renamed)
  6757. :param state: what was done with the objectCand be: added, deleted, delete_all, renamed
  6758. :param old_name: the old name of the object before the action that triggered this slot happened
  6759. :return: None
  6760. """
  6761. icon_files = {
  6762. "gerber": "share/flatcam_icon16.png",
  6763. "excellon": "share/drill16.png",
  6764. "cncjob": "share/cnc16.png",
  6765. "geometry": "share/geometry16.png",
  6766. "script": "share/script_new16.png",
  6767. "document": "share/notes16_1.png"
  6768. }
  6769. if state == 'append':
  6770. for act in self.ui.menuobjects.actions():
  6771. try:
  6772. act.triggered.disconnect()
  6773. except TypeError:
  6774. pass
  6775. self.ui.menuobjects.clear()
  6776. gerber_list = list()
  6777. exc_list = list()
  6778. cncjob_list = list()
  6779. geo_list = list()
  6780. script_list = list()
  6781. doc_list = list()
  6782. for name in self.collection.get_names():
  6783. obj_named = self.collection.get_by_name(name)
  6784. if obj_named.kind == 'gerber':
  6785. gerber_list.append(name)
  6786. elif obj_named.kind == 'excellon':
  6787. exc_list.append(name)
  6788. elif obj_named.kind == 'cncjob':
  6789. cncjob_list.append(name)
  6790. elif obj_named.kind == 'geometry':
  6791. geo_list.append(name)
  6792. elif obj_named.kind == 'script':
  6793. script_list.append(name)
  6794. elif obj_named.kind == 'document':
  6795. doc_list.append(name)
  6796. def add_act(name):
  6797. obj_for_icon = self.collection.get_by_name(name)
  6798. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6799. add_action.setCheckable(True)
  6800. add_action.setText(name)
  6801. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  6802. add_action.triggered.connect(
  6803. lambda: self.collection.set_active(name) if add_action.isChecked() is True else
  6804. self.collection.set_inactive(name))
  6805. self.ui.menuobjects.addAction(add_action)
  6806. for name in gerber_list:
  6807. add_act(name)
  6808. self.ui.menuobjects.addSeparator()
  6809. for name in exc_list:
  6810. add_act(name)
  6811. self.ui.menuobjects.addSeparator()
  6812. for name in cncjob_list:
  6813. add_act(name)
  6814. self.ui.menuobjects.addSeparator()
  6815. for name in geo_list:
  6816. add_act(name)
  6817. self.ui.menuobjects.addSeparator()
  6818. for name in script_list:
  6819. add_act(name)
  6820. self.ui.menuobjects.addSeparator()
  6821. for name in doc_list:
  6822. add_act(name)
  6823. self.ui.menuobjects.addSeparator()
  6824. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  6825. QtGui.QIcon('share/select_all.png'),
  6826. _('Select All')
  6827. )
  6828. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  6829. QtGui.QIcon('share/deselect_all32.png'),
  6830. _('Deselect All')
  6831. )
  6832. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  6833. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  6834. elif state == 'delete':
  6835. for act in self.ui.menuobjects.actions():
  6836. if act.text() == obj.options['name']:
  6837. try:
  6838. act.triggered.disconnect()
  6839. except TypeError:
  6840. pass
  6841. self.ui.menuobjects.removeAction(act)
  6842. break
  6843. elif state == 'rename':
  6844. for act in self.ui.menuobjects.actions():
  6845. if act.text() == old_name:
  6846. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6847. add_action.setText(obj.options['name'])
  6848. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  6849. add_action.triggered.connect(
  6850. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  6851. self.collection.set_inactive(obj.options['name']))
  6852. self.ui.menuobjects.insertAction(act, add_action)
  6853. try:
  6854. act.triggered.disconnect()
  6855. except TypeError:
  6856. pass
  6857. self.ui.menuobjects.removeAction(act)
  6858. break
  6859. elif state =='delete_all':
  6860. for act in self.ui.menuobjects.actions():
  6861. try:
  6862. act.triggered.disconnect()
  6863. except TypeError:
  6864. pass
  6865. self.ui.menuobjects.clear()
  6866. self.ui.menuobjects.addSeparator()
  6867. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  6868. QtGui.QIcon('share/select_all.png'),
  6869. _('Select All')
  6870. )
  6871. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  6872. QtGui.QIcon('share/deselect_all32.png'),
  6873. _('Deselect All')
  6874. )
  6875. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  6876. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  6877. def on_objects_selection(self, on_off):
  6878. obj_list = self.collection.get_names()
  6879. if on_off is True:
  6880. self.collection.set_all_active()
  6881. for act in self.ui.menuobjects.actions():
  6882. try:
  6883. act.setChecked(True)
  6884. except:
  6885. pass
  6886. if obj_list:
  6887. self.inform.emit('[selected] %s' % _("All objects are selected."))
  6888. else:
  6889. self.collection.set_all_inactive()
  6890. for act in self.ui.menuobjects.actions():
  6891. try:
  6892. act.setChecked(False)
  6893. except:
  6894. pass
  6895. self.inform.emit('%s' % _("Objects selection is cleared."))
  6896. def grid_status(self):
  6897. if self.ui.grid_snap_btn.isChecked():
  6898. return True
  6899. else:
  6900. return False
  6901. def populate_cmenu_grids(self):
  6902. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6903. self.ui.cmenu_gridmenu.clear()
  6904. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  6905. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  6906. grid_toggle.setCheckable(True)
  6907. if self.grid_status() == True:
  6908. grid_toggle.setChecked(True)
  6909. else:
  6910. grid_toggle.setChecked(False)
  6911. self.ui.cmenu_gridmenu.addSeparator()
  6912. for grid in sorted_list:
  6913. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  6914. action.triggered.connect(self.set_grid)
  6915. self.ui.cmenu_gridmenu.addSeparator()
  6916. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  6917. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  6918. grid_add.triggered.connect(self.on_grid_add)
  6919. grid_delete.triggered.connect(self.on_grid_delete)
  6920. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  6921. def set_grid(self):
  6922. self.ui.grid_gap_x_entry.setText(self.sender().text())
  6923. self.ui.grid_gap_y_entry.setText(self.sender().text())
  6924. def on_grid_add(self):
  6925. # ## Current application units in lower Case
  6926. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6927. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  6928. text=_('Enter a Grid Value:'),
  6929. min=0.0000, max=99.9999, decimals=4)
  6930. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  6931. val, ok = grid_add_popup.get_value()
  6932. if ok:
  6933. if float(val) == 0:
  6934. self.inform.emit('[WARNING_NOTCL] %s' %
  6935. _("Please enter a grid value with non-zero value, in Float format."))
  6936. return
  6937. else:
  6938. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  6939. self.defaults["global_grid_context_menu"][str(units)].append(val)
  6940. self.inform.emit('[success] %s...' %
  6941. _("New Grid added"))
  6942. else:
  6943. self.inform.emit('[WARNING_NOTCL] %s...' %
  6944. _("Grid already exists"))
  6945. else:
  6946. self.inform.emit('[WARNING_NOTCL] %s...' %
  6947. _("Adding New Grid cancelled"))
  6948. def on_grid_delete(self):
  6949. # ## Current application units in lower Case
  6950. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6951. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  6952. text='Enter a Grid Value:',
  6953. min=0.0000, max=99.9999, decimals=4)
  6954. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  6955. val, ok = grid_del_popup.get_value()
  6956. if ok:
  6957. if float(val) == 0:
  6958. self.inform.emit('[WARNING_NOTCL] %s' %
  6959. _("Please enter a grid value with non-zero value, in Float format."))
  6960. return
  6961. else:
  6962. try:
  6963. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  6964. except ValueError:
  6965. self.inform.emit('[ERROR_NOTCL]%s...' %
  6966. _(" Grid Value does not exist"))
  6967. return
  6968. self.inform.emit('[success] %s...' %
  6969. _("Grid Value deleted"))
  6970. else:
  6971. self.inform.emit('[WARNING_NOTCL] %s...' %
  6972. _("Delete Grid value cancelled"))
  6973. def on_shortcut_list(self):
  6974. self.report_usage("on_shortcut_list()")
  6975. # add the tab if it was closed
  6976. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  6977. # delete the absolute and relative position and messages in the infobar
  6978. self.ui.position_label.setText("")
  6979. self.ui.rel_position_label.setText("")
  6980. # Switch plot_area to preferences page
  6981. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  6982. # self.ui.show()
  6983. def on_select_tab(self, name):
  6984. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  6985. if self.ui.splitter.sizes()[0] == 0:
  6986. self.ui.splitter.setSizes([1, 1])
  6987. else:
  6988. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  6989. self.ui.splitter.setSizes([0, 1])
  6990. if name == 'project':
  6991. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6992. elif name == 'selected':
  6993. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6994. elif name == 'tool':
  6995. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  6996. def on_copy_name(self):
  6997. self.report_usage("on_copy_name()")
  6998. obj = self.collection.get_active()
  6999. try:
  7000. name = obj.options["name"]
  7001. except AttributeError:
  7002. log.debug("on_copy_name() --> No object selected to copy it's name")
  7003. self.inform.emit('[WARNING_NOTCL]%s' %
  7004. _(" No object selected to copy it's name"))
  7005. return
  7006. self.clipboard.setText(name)
  7007. self.inform.emit(_("Name copied on clipboard ..."))
  7008. def on_mouse_click_over_plot(self, event):
  7009. """
  7010. Default actions are:
  7011. :param event: Contains information about the event, like which button
  7012. was clicked, the pixel coordinates and the axes coordinates.
  7013. :return: None
  7014. """
  7015. self.pos = []
  7016. if self.is_legacy is False:
  7017. event_pos = event.pos
  7018. if self.defaults["global_pan_button"] == '2':
  7019. pan_button = 2
  7020. else:
  7021. pan_button = 3
  7022. # Set the mouse button for panning
  7023. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7024. else:
  7025. event_pos = (event.xdata, event.ydata)
  7026. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7027. if self.defaults["global_pan_button"] == '2':
  7028. pan_button = 3
  7029. else:
  7030. pan_button = 2
  7031. # So it can receive key presses
  7032. self.plotcanvas.native.setFocus()
  7033. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7034. if self.grid_status() == True:
  7035. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  7036. else:
  7037. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  7038. try:
  7039. if event.button == 1:
  7040. # Reset here the relative coordinates so there is a new reference on the click position
  7041. if self.rel_point1 is None:
  7042. self.rel_point1 = self.pos
  7043. else:
  7044. self.rel_point2 = copy(self.rel_point1)
  7045. self.rel_point1 = self.pos
  7046. self.on_mouse_move_over_plot(event, origin_click=True)
  7047. except Exception as e:
  7048. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  7049. def on_mouse_double_click_over_plot(self, event):
  7050. if event.button == 1:
  7051. self.doubleclick = True
  7052. def on_mouse_move_over_plot(self, event, origin_click=None):
  7053. """
  7054. Callback for the mouse motion event over the plot.
  7055. :param event: Contains information about the event.
  7056. :param origin_click
  7057. :return: None
  7058. """
  7059. if self.is_legacy is False:
  7060. event_pos = event.pos
  7061. if self.defaults["global_pan_button"] == '2':
  7062. pan_button = 2
  7063. else:
  7064. pan_button = 3
  7065. event_is_dragging = event.is_dragging
  7066. else:
  7067. event_pos = (event.xdata, event.ydata)
  7068. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7069. if self.defaults["global_pan_button"] == '2':
  7070. pan_button = 3
  7071. else:
  7072. pan_button = 2
  7073. event_is_dragging = self.plotcanvas.is_dragging
  7074. # So it can receive key presses
  7075. self.plotcanvas.native.setFocus()
  7076. self.pos_jump = event_pos
  7077. self.ui.popMenu.mouse_is_panning = False
  7078. if not origin_click:
  7079. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  7080. if event.button == pan_button and event_is_dragging == 1:
  7081. self.ui.popMenu.mouse_is_panning = True
  7082. return
  7083. if self.rel_point1 is not None:
  7084. try: # May fail in case mouse not within axes
  7085. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7086. if self.grid_status() == True:
  7087. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  7088. # Update cursor
  7089. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  7090. symbol='++', edge_color=self.cursor_color_3D,
  7091. size=self.defaults["global_cursor_size"])
  7092. else:
  7093. pos = (pos_canvas[0], pos_canvas[1])
  7094. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  7095. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  7096. dx = pos[0] - float(self.rel_point1[0])
  7097. dy = pos[1] - float(self.rel_point1[1])
  7098. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  7099. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  7100. self.mouse = [pos[0], pos[1]]
  7101. # if the mouse is moved and the LMB is clicked then the action is a selection
  7102. if event_is_dragging == 1 and event.button == 1:
  7103. self.delete_selection_shape()
  7104. if dx < 0:
  7105. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  7106. face_color=self.defaults['global_alt_sel_fill'])
  7107. self.selection_type = False
  7108. elif dx > 0:
  7109. self.draw_moving_selection_shape(self.pos, pos)
  7110. self.selection_type = True
  7111. else:
  7112. self.selection_type = None
  7113. # hover effect - enabled in Preferences -> General -> GUI Settings
  7114. if self.defaults['global_hover']:
  7115. for obj in self.collection.get_list():
  7116. try:
  7117. # select the object(s) only if it is enabled (plotted)
  7118. if obj.options['plot']:
  7119. if obj not in self.collection.get_selected():
  7120. poly_obj = Polygon(
  7121. [(obj.options['xmin'], obj.options['ymin']),
  7122. (obj.options['xmax'], obj.options['ymin']),
  7123. (obj.options['xmax'], obj.options['ymax']),
  7124. (obj.options['xmin'], obj.options['ymax'])]
  7125. )
  7126. if Point(pos).within(poly_obj):
  7127. if obj.isHovering is False:
  7128. obj.isHovering = True
  7129. obj.notHovering = True
  7130. # create the selection box around the selected object
  7131. self.draw_hover_shape(obj, color='#d1e0e0FF')
  7132. else:
  7133. if obj.notHovering is True:
  7134. obj.notHovering = False
  7135. obj.isHovering = False
  7136. self.delete_hover_shape()
  7137. except:
  7138. # the Exception here will happen if we try to select on screen and we have an
  7139. # newly (and empty) just created Geometry or Excellon object that do not have the
  7140. # xmin, xmax, ymin, ymax options.
  7141. # In this case poly_obj creation (see above) will fail
  7142. pass
  7143. except:
  7144. self.ui.position_label.setText("")
  7145. self.ui.rel_position_label.setText("")
  7146. self.mouse = None
  7147. def on_mouse_click_release_over_plot(self, event):
  7148. """
  7149. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  7150. and has been registered in ''self.__init__()''.
  7151. :param event: contains information about the event.
  7152. :return:
  7153. """
  7154. pos = 0, 0
  7155. if self.is_legacy is False:
  7156. event_pos = event.pos
  7157. right_button = 2
  7158. else:
  7159. event_pos = (event.xdata, event.ydata)
  7160. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7161. right_button = 3
  7162. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7163. if self.grid_status() == True:
  7164. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  7165. else:
  7166. pos = (pos_canvas[0], pos_canvas[1])
  7167. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  7168. # canvas menu
  7169. if event.button == right_button: # right click
  7170. if self.ui.popMenu.mouse_is_panning is False:
  7171. self.cursor = QtGui.QCursor()
  7172. self.populate_cmenu_grids()
  7173. self.ui.popMenu.popup(self.cursor.pos())
  7174. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  7175. # selection and then select a type of selection ("enclosing" or "touching")
  7176. try:
  7177. if event.button == 1: # left click
  7178. modifiers = QtWidgets.QApplication.keyboardModifiers()
  7179. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  7180. if modifiers == QtCore.Qt.ShiftModifier:
  7181. # do not auto open the Project Tab
  7182. self.click_noproject = True
  7183. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  7184. self.inform.emit('[success] %s' %
  7185. _("Coordinates copied to clipboard."))
  7186. return
  7187. if self.doubleclick is True:
  7188. self.doubleclick = False
  7189. if self.collection.get_selected():
  7190. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  7191. if self.ui.splitter.sizes()[0] == 0:
  7192. self.ui.splitter.setSizes([1, 1])
  7193. # delete the selection shape(S) as it may be in the way
  7194. self.delete_selection_shape()
  7195. self.delete_hover_shape()
  7196. else:
  7197. if self.selection_type is not None:
  7198. self.selection_area_handler(self.pos, pos, self.selection_type)
  7199. self.selection_type = None
  7200. else:
  7201. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  7202. if key_modifier == QtCore.Qt.ShiftModifier:
  7203. mod_key = 'Shift'
  7204. elif key_modifier == QtCore.Qt.ControlModifier:
  7205. mod_key = 'Control'
  7206. else:
  7207. mod_key = None
  7208. if mod_key == self.defaults["global_mselect_key"]:
  7209. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  7210. # deselect, and if it's not selected then it will be selected
  7211. # If there is no active command (self.command_active is None) then we check if we clicked
  7212. # on a object by checking the bounding limits against mouse click position
  7213. if self.command_active is None:
  7214. self.select_objects(key='CTRL')
  7215. self.delete_hover_shape()
  7216. else:
  7217. # If there is no active command (self.command_active is None) then we check if we clicked
  7218. # on a object by checking the bounding limits against mouse click position
  7219. if self.command_active is None:
  7220. self.select_objects()
  7221. self.delete_hover_shape()
  7222. except Exception as e:
  7223. log.warning("Error: %s" % str(e))
  7224. return
  7225. def selection_area_handler(self, start_pos, end_pos, sel_type):
  7226. """
  7227. :param start_pos: mouse position when the selection LMB click was done
  7228. :param end_pos: mouse position when the left mouse button is released
  7229. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  7230. :return:
  7231. """
  7232. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  7233. # delete previous selection shape
  7234. self.delete_selection_shape()
  7235. # make all objects inactive
  7236. self.collection.set_all_inactive()
  7237. for obj in self.collection.get_list():
  7238. try:
  7239. # select the object(s) only if it is enabled (plotted)
  7240. if obj.options['plot']:
  7241. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  7242. (obj.options['xmax'], obj.options['ymin']),
  7243. (obj.options['xmax'], obj.options['ymax']),
  7244. (obj.options['xmin'], obj.options['ymax'])])
  7245. if sel_type is True:
  7246. if poly_obj.within(poly_selection):
  7247. # create the selection box around the selected object
  7248. if self.defaults['global_selection_shape'] is True:
  7249. self.draw_selection_shape(obj)
  7250. self.collection.set_active(obj.options['name'])
  7251. else:
  7252. if poly_selection.intersects(poly_obj):
  7253. # create the selection box around the selected object
  7254. if self.defaults['global_selection_shape'] is True:
  7255. self.draw_selection_shape(obj)
  7256. self.collection.set_active(obj.options['name'])
  7257. except Exception as e:
  7258. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  7259. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  7260. # In this case poly_obj creation (see above) will fail
  7261. log.debug("App.selection_area_handler() --> %s" % str(e))
  7262. def select_objects(self, key=None):
  7263. # list where we store the overlapped objects under our mouse left click position
  7264. objects_under_the_click_list = []
  7265. # Populate the list with the overlapped objects on the click position
  7266. curr_x, curr_y = self.pos
  7267. for obj in self.all_objects_list:
  7268. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  7269. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  7270. if obj.options['name'] not in objects_under_the_click_list:
  7271. if obj.options['plot']:
  7272. # add objects to the objects_under_the_click list only if the object is plotted
  7273. # (active and not disabled)
  7274. objects_under_the_click_list.append(obj.options['name'])
  7275. try:
  7276. if objects_under_the_click_list:
  7277. curr_sel_obj = self.collection.get_active()
  7278. # case when there is only an object under the click and we toggle it
  7279. if len(objects_under_the_click_list) == 1:
  7280. if curr_sel_obj is None:
  7281. self.collection.set_active(objects_under_the_click_list[0])
  7282. curr_sel_obj = self.collection.get_active()
  7283. # create the selection box around the selected object
  7284. if self.defaults['global_selection_shape'] is True:
  7285. self.draw_selection_shape(curr_sel_obj)
  7286. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  7287. self.on_objects_selection(False)
  7288. self.delete_selection_shape()
  7289. self.collection.set_active(objects_under_the_click_list[0])
  7290. curr_sel_obj = self.collection.get_active()
  7291. # create the selection box around the selected object
  7292. if self.defaults['global_selection_shape'] is True:
  7293. self.draw_selection_shape(curr_sel_obj)
  7294. self.selected_message(curr_sel_obj=curr_sel_obj)
  7295. else:
  7296. self.on_objects_selection(False)
  7297. self.delete_selection_shape()
  7298. if self.call_source != 'app':
  7299. self.call_source = 'app'
  7300. self.selected_message(curr_sel_obj=curr_sel_obj)
  7301. else:
  7302. # If there is no selected object
  7303. # make active the first element of the overlapped objects list
  7304. if self.collection.get_active() is None:
  7305. self.collection.set_active(objects_under_the_click_list[0])
  7306. name_sel_obj = self.collection.get_active().options['name']
  7307. # In case that there is a selected object but it is not in the overlapped object list
  7308. # make that object inactive and activate the first element in the overlapped object list
  7309. if name_sel_obj not in objects_under_the_click_list:
  7310. self.collection.set_inactive(name_sel_obj)
  7311. name_sel_obj = objects_under_the_click_list[0]
  7312. self.collection.set_active(name_sel_obj)
  7313. else:
  7314. sel_idx = objects_under_the_click_list.index(name_sel_obj)
  7315. self.collection.set_all_inactive()
  7316. self.collection.set_active(objects_under_the_click_list[(sel_idx + 1) %
  7317. len(objects_under_the_click_list)])
  7318. curr_sel_obj = self.collection.get_active()
  7319. # delete the possible selection box around a possible selected object
  7320. self.delete_selection_shape()
  7321. # create the selection box around the selected object
  7322. if self.defaults['global_selection_shape'] is True:
  7323. self.draw_selection_shape(curr_sel_obj)
  7324. self.selected_message(curr_sel_obj=curr_sel_obj)
  7325. else:
  7326. # deselect everything
  7327. self.on_objects_selection(False)
  7328. # delete the possible selection box around a possible selected object
  7329. self.delete_selection_shape()
  7330. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  7331. # only when working on App
  7332. if self.call_source == 'app':
  7333. if self.click_noproject is False:
  7334. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7335. else:
  7336. # restore auto open the Project Tab
  7337. self.click_noproject = False
  7338. # delete any text in the status bar, implicitly the last object name that was selected
  7339. # self.inform.emit("")
  7340. else:
  7341. self.call_source = 'app'
  7342. except Exception as e:
  7343. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  7344. def selected_message(self, curr_sel_obj):
  7345. if curr_sel_obj:
  7346. if curr_sel_obj.kind == 'gerber':
  7347. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7348. color='green', name=str(curr_sel_obj.options['name'])))
  7349. elif curr_sel_obj.kind == 'excellon':
  7350. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7351. color='brown', name=str(curr_sel_obj.options['name'])))
  7352. elif curr_sel_obj.kind == 'cncjob':
  7353. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7354. color='blue', name=str(curr_sel_obj.options['name'])))
  7355. elif curr_sel_obj.kind == 'geometry':
  7356. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7357. color='red', name=str(curr_sel_obj.options['name'])))
  7358. def delete_hover_shape(self):
  7359. self.hover_shapes.clear()
  7360. self.hover_shapes.redraw()
  7361. def draw_hover_shape(self, sel_obj, color=None):
  7362. """
  7363. :param sel_obj: the object for which the hover shape must be drawn
  7364. :return:
  7365. """
  7366. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7367. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7368. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7369. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7370. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  7371. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  7372. hover_rect = hover_rect.buffer(-0.1)
  7373. hover_rect = hover_rect.buffer(0.2)
  7374. else:
  7375. hover_rect = hover_rect.buffer(-0.00393)
  7376. hover_rect = hover_rect.buffer(0.00787)
  7377. # if color:
  7378. # face = Color(color)
  7379. # face.alpha = 0.2
  7380. # outline = Color(color, alpha=0.8)
  7381. # else:
  7382. # face = Color(self.defaults['global_sel_fill'])
  7383. # face.alpha = 0.2
  7384. # outline = self.defaults['global_sel_line']
  7385. if color:
  7386. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7387. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7388. else:
  7389. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7390. outline = self.defaults['global_sel_line']
  7391. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  7392. if self.is_legacy is True:
  7393. self.hover_shapes.redraw()
  7394. def delete_selection_shape(self):
  7395. self.move_tool.sel_shapes.clear()
  7396. self.move_tool.sel_shapes.redraw()
  7397. def draw_selection_shape(self, sel_obj, color=None):
  7398. """
  7399. :param sel_obj: the object for which the selection shape must be drawn
  7400. :return:
  7401. """
  7402. if sel_obj is None:
  7403. return
  7404. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7405. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7406. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7407. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7408. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7409. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  7410. sel_rect = sel_rect.buffer(-0.1)
  7411. sel_rect = sel_rect.buffer(0.2)
  7412. else:
  7413. sel_rect = sel_rect.buffer(-0.00393)
  7414. sel_rect = sel_rect.buffer(0.00787)
  7415. if color:
  7416. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7417. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7418. else:
  7419. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7420. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  7421. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  7422. color=outline,
  7423. face_color=face,
  7424. update=True,
  7425. layer=0,
  7426. tolerance=None))
  7427. if self.is_legacy is True:
  7428. self.move_tool.sel_shapes.redraw()
  7429. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  7430. """
  7431. :param old_coords: old coordinates
  7432. :param coords: new coordinates
  7433. :return:
  7434. """
  7435. if 'color' in kwargs:
  7436. color = kwargs['color']
  7437. else:
  7438. color = self.defaults['global_sel_line']
  7439. if 'face_color' in kwargs:
  7440. face_color = kwargs['face_color']
  7441. else:
  7442. face_color = self.defaults['global_sel_fill']
  7443. if 'face_alpha' in kwargs:
  7444. face_alpha = kwargs['face_alpha']
  7445. else:
  7446. face_alpha = 0.3
  7447. x0, y0 = old_coords
  7448. x1, y1 = coords
  7449. pt1 = (x0, y0)
  7450. pt2 = (x1, y0)
  7451. pt3 = (x1, y1)
  7452. pt4 = (x0, y1)
  7453. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7454. # color_t = Color(face_color)
  7455. # color_t.alpha = face_alpha
  7456. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  7457. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  7458. layer=0, tolerance=None)
  7459. if self.is_legacy is True:
  7460. self.move_tool.sel_shapes.redraw()
  7461. def on_file_new_click(self):
  7462. if self.collection.get_list() and self.should_we_save:
  7463. msgbox = QtWidgets.QMessageBox()
  7464. # msgbox.setText("<B>Save changes ...</B>")
  7465. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7466. "Creating a New project will delete them.\n"
  7467. "Do you want to Save the project?"))
  7468. msgbox.setWindowTitle(_("Save changes"))
  7469. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  7470. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7471. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7472. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7473. msgbox.setDefaultButton(bt_yes)
  7474. msgbox.exec_()
  7475. response = msgbox.clickedButton()
  7476. if response == bt_yes:
  7477. self.on_file_saveprojectas()
  7478. elif response == bt_cancel:
  7479. return
  7480. elif response == bt_no:
  7481. self.on_file_new()
  7482. else:
  7483. self.on_file_new()
  7484. self.inform.emit('[success] %s...' %
  7485. _("New Project created"))
  7486. def on_file_new(self, cli=None):
  7487. """
  7488. Callback for menu item File->New. Returns the application to its
  7489. startup state. This method is thread-safe.
  7490. :return: None
  7491. """
  7492. self.report_usage("on_file_new")
  7493. # Remove everything from memory
  7494. App.log.debug("on_file_new()")
  7495. if self.call_source != 'app':
  7496. self.editor2object(cleanup=True)
  7497. # ## EDITOR section
  7498. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  7499. self.exc_editor = FlatCAMExcEditor(self)
  7500. self.grb_editor = FlatCAMGrbEditor(self)
  7501. # Clear pool
  7502. self.clear_pool()
  7503. for obj in self.collection.get_list():
  7504. # delete shapes left drawn from mark shape_collections, if any
  7505. if isinstance(obj, FlatCAMGerber):
  7506. try:
  7507. obj.mark_shapes.enabled = False
  7508. obj.mark_shapes.clear(update=True)
  7509. except AttributeError:
  7510. pass
  7511. # also delete annotation shapes, if any
  7512. elif isinstance(obj, FlatCAMCNCjob):
  7513. try:
  7514. obj.annotation.enabled = False
  7515. obj.annotation.clear(update=True)
  7516. except AttributeError:
  7517. pass
  7518. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7519. self.init_tcl()
  7520. self.delete_selection_shape()
  7521. self.collection.delete_all()
  7522. self.setup_component_editor()
  7523. # Clear project filename
  7524. self.project_filename = None
  7525. # Load the application defaults
  7526. self.load_defaults(filename='current_defaults')
  7527. # Re-fresh project options
  7528. self.on_options_app2project()
  7529. # Init Tools
  7530. self.init_tools()
  7531. if cli is None:
  7532. # Close any Tabs opened in the Plot Tab Area section
  7533. for index in range(self.ui.plot_tab_area.count()):
  7534. self.ui.plot_tab_area.closeTab(index)
  7535. # for whatever reason previous command does not close the last tab so I do it manually
  7536. self.ui.plot_tab_area.closeTab(0)
  7537. # # And then add again the Plot Area
  7538. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  7539. self.ui.plot_tab_area.protectTab(0)
  7540. # take the focus of the Notebook on Project Tab.
  7541. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7542. self.set_ui_title(name=_("New Project - Not saved"))
  7543. def obj_properties(self):
  7544. self.report_usage("obj_properties()")
  7545. self.properties_tool.run(toggle=False)
  7546. def on_project_context_save(self):
  7547. obj = self.collection.get_active()
  7548. if type(obj) == FlatCAMGeometry:
  7549. self.on_file_exportdxf()
  7550. elif type(obj) == FlatCAMExcellon:
  7551. self.on_file_saveexcellon()
  7552. elif type(obj) == FlatCAMCNCjob:
  7553. obj.on_exportgcode_button_click()
  7554. elif type(obj) == FlatCAMGerber:
  7555. self.on_file_savegerber()
  7556. elif type(obj) == FlatCAMScript:
  7557. self.on_file_savescript()
  7558. elif type(obj) == FlatCAMDocument:
  7559. self.on_file_savedocument()
  7560. def obj_move(self):
  7561. self.report_usage("obj_move()")
  7562. self.move_tool.run(toggle=False)
  7563. def on_fileopengerber(self, checked=None, name=None):
  7564. """
  7565. File menu callback for opening a Gerber.
  7566. :return: None
  7567. """
  7568. self.report_usage("on_fileopengerber")
  7569. App.log.debug("on_fileopengerber()")
  7570. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  7571. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  7572. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  7573. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  7574. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  7575. "*.mil);;" \
  7576. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  7577. "Allegro Files (*.art);;" \
  7578. "Mentor Files (*.pho *.gdo);;" \
  7579. "All Files (*.*)"
  7580. if name is None:
  7581. try:
  7582. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  7583. directory=self.get_last_folder(),
  7584. filter=_filter_)
  7585. except TypeError:
  7586. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  7587. filenames = [str(filename) for filename in filenames]
  7588. else:
  7589. filenames = [name]
  7590. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7591. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7592. _("Opening Gerber file.")),
  7593. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7594. color=QtGui.QColor("gray"))
  7595. if len(filenames) == 0:
  7596. self.inform.emit('[WARNING_NOTCL] %s' %
  7597. _("Open Gerber cancelled."))
  7598. else:
  7599. for filename in filenames:
  7600. if filename != '':
  7601. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  7602. def on_fileopenexcellon(self, checked=None, name=None):
  7603. """
  7604. File menu callback for opening an Excellon file.
  7605. :return: None
  7606. """
  7607. self.report_usage("on_fileopenexcellon")
  7608. App.log.debug("on_fileopenexcellon()")
  7609. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  7610. "All Files (*.*)"
  7611. if name is None:
  7612. try:
  7613. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  7614. directory=self.get_last_folder(),
  7615. filter=_filter_)
  7616. except TypeError:
  7617. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  7618. filenames = [str(filename) for filename in filenames]
  7619. else:
  7620. filenames = [str(name)]
  7621. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7622. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7623. _("Opening Excellon file.")),
  7624. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7625. color=QtGui.QColor("gray"))
  7626. if len(filenames) == 0:
  7627. self.inform.emit('[WARNING_NOTCL]%s' %
  7628. _(" Open Excellon cancelled."))
  7629. else:
  7630. for filename in filenames:
  7631. if filename != '':
  7632. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  7633. def on_fileopengcode(self, checked=None, name=None):
  7634. """
  7635. File menu call back for opening gcode.
  7636. :return: None
  7637. """
  7638. self.report_usage("on_fileopengcode")
  7639. App.log.debug("on_fileopengcode()")
  7640. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  7641. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  7642. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  7643. "All Files (*.*)"
  7644. if name is None:
  7645. try:
  7646. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  7647. directory=self.get_last_folder(),
  7648. filter=_filter_)
  7649. except TypeError:
  7650. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  7651. filenames = [str(filename) for filename in filenames]
  7652. else:
  7653. filenames = [name]
  7654. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7655. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7656. _("Opening G-Code file.")),
  7657. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7658. color=QtGui.QColor("gray"))
  7659. if len(filenames) == 0:
  7660. self.inform.emit('[WARNING_NOTCL] %s' %
  7661. _("Open G-Code cancelled."))
  7662. else:
  7663. for filename in filenames:
  7664. if filename != '':
  7665. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  7666. def on_file_openproject(self, checked=None):
  7667. """
  7668. File menu callback for opening a project.
  7669. :return: None
  7670. """
  7671. self.report_usage("on_file_openproject")
  7672. App.log.debug("on_file_openproject()")
  7673. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  7674. try:
  7675. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  7676. directory=self.get_last_folder(), filter=_filter_)
  7677. except TypeError:
  7678. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  7679. # The Qt methods above will return a QString which can cause problems later.
  7680. # So far json.dump() will fail to serialize it.
  7681. # TODO: Improve the serialization methods and remove this fix.
  7682. filename = str(filename)
  7683. if filename == "":
  7684. self.inform.emit('[WARNING_NOTCL] %s' %
  7685. _("Open Project cancelled."))
  7686. else:
  7687. # self.worker_task.emit({'fcn': self.open_project,
  7688. # 'params': [filename]})
  7689. # The above was failing because open_project() is not
  7690. # thread safe. The new_project()
  7691. self.open_project(filename)
  7692. def on_file_openconfig(self, checked=None):
  7693. """
  7694. File menu callback for opening a config file.
  7695. :return: None
  7696. """
  7697. self.report_usage("on_file_openconfig")
  7698. App.log.debug("on_file_openconfig()")
  7699. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  7700. try:
  7701. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7702. directory=self.data_path, filter=_filter_)
  7703. except TypeError:
  7704. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7705. filter=_filter_)
  7706. if filename == "":
  7707. self.inform.emit('[WARNING_NOTCL] %s' %
  7708. _("Open Config cancelled."))
  7709. else:
  7710. self.open_config_file(filename)
  7711. def on_file_exportsvg(self):
  7712. """
  7713. Callback for menu item File->Export SVG.
  7714. :return: None
  7715. """
  7716. self.report_usage("on_file_exportsvg")
  7717. App.log.debug("on_file_exportsvg()")
  7718. obj = self.collection.get_active()
  7719. if obj is None:
  7720. self.inform.emit('[WARNING_NOTCL] %s' %
  7721. _("No object selected."))
  7722. msg = _("Please Select a Geometry object to export")
  7723. msgbox = QtWidgets.QMessageBox()
  7724. msgbox.setInformativeText(msg)
  7725. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7726. msgbox.setDefaultButton(bt_ok)
  7727. msgbox.exec_()
  7728. return
  7729. # Check for more compatible types and add as required
  7730. if (not isinstance(obj, FlatCAMGeometry)
  7731. and not isinstance(obj, FlatCAMGerber)
  7732. and not isinstance(obj, FlatCAMCNCjob)
  7733. and not isinstance(obj, FlatCAMExcellon)):
  7734. msg = '[ERROR_NOTCL] %s' % \
  7735. _("Only Geometry, Gerber and CNCJob objects can be used.")
  7736. msgbox = QtWidgets.QMessageBox()
  7737. msgbox.setInformativeText(msg)
  7738. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7739. msgbox.setDefaultButton(bt_ok)
  7740. msgbox.exec_()
  7741. return
  7742. name = obj.options["name"]
  7743. _filter = "SVG File (*.svg);;All Files (*.*)"
  7744. try:
  7745. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7746. caption=_("Export SVG"),
  7747. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  7748. filter=_filter)
  7749. except TypeError:
  7750. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  7751. filename = str(filename)
  7752. if filename == "":
  7753. self.inform.emit('[WARNING_NOTCL]%s' %
  7754. _(" Export SVG cancelled."))
  7755. return
  7756. else:
  7757. self.export_svg(name, filename)
  7758. if self.defaults["global_open_style"] is False:
  7759. self.file_opened.emit("SVG", filename)
  7760. self.file_saved.emit("SVG", filename)
  7761. def on_file_exportpng(self):
  7762. self.report_usage("on_file_exportpng")
  7763. App.log.debug("on_file_exportpng()")
  7764. self.date = str(datetime.today()).rpartition('.')[0]
  7765. self.date = ''.join(c for c in self.date if c not in ':-')
  7766. self.date = self.date.replace(' ', '_')
  7767. if self.is_legacy is False:
  7768. image = _screenshot()
  7769. data = np.asarray(image)
  7770. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  7771. self.inform.emit('[[WARNING_NOTCL]] %s' %
  7772. _('Data must be a 3D array with last dimension 3 or 4'))
  7773. return
  7774. filter_ = "PNG File (*.png);;All Files (*.*)"
  7775. try:
  7776. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7777. caption=_("Export PNG Image"),
  7778. directory=self.get_last_save_folder() + '/png_' + self.date,
  7779. filter=filter_)
  7780. except TypeError:
  7781. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  7782. filename = str(filename)
  7783. if filename == "":
  7784. self.inform.emit(_("Export PNG cancelled."))
  7785. return
  7786. else:
  7787. if self.is_legacy is False:
  7788. write_png(filename, data)
  7789. else:
  7790. self.plotcanvas.figure.savefig(filename)
  7791. if self.defaults["global_open_style"] is False:
  7792. self.file_opened.emit("png", filename)
  7793. self.file_saved.emit("png", filename)
  7794. def on_file_savegerber(self):
  7795. """
  7796. Callback for menu item in Project context menu.
  7797. :return: None
  7798. """
  7799. self.report_usage("on_file_savegerber")
  7800. App.log.debug("on_file_savegerber()")
  7801. obj = self.collection.get_active()
  7802. if obj is None:
  7803. self.inform.emit('[WARNING_NOTCL] %s' %
  7804. _("No object selected. Please select an Gerber object to export."))
  7805. return
  7806. # Check for more compatible types and add as required
  7807. if not isinstance(obj, FlatCAMGerber):
  7808. self.inform.emit('[ERROR_NOTCL] %s' %
  7809. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7810. return
  7811. name = self.collection.get_active().options["name"]
  7812. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7813. try:
  7814. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7815. caption="Save Gerber source file",
  7816. directory=self.get_last_save_folder() + '/' + name,
  7817. filter=_filter)
  7818. except TypeError:
  7819. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  7820. filename = str(filename)
  7821. if filename == "":
  7822. self.inform.emit('[WARNING_NOTCL] %s' %
  7823. _("Save Gerber source file cancelled."))
  7824. return
  7825. else:
  7826. self.save_source_file(name, filename)
  7827. if self.defaults["global_open_style"] is False:
  7828. self.file_opened.emit("Gerber", filename)
  7829. self.file_saved.emit("Gerber", filename)
  7830. def on_file_savescript(self):
  7831. """
  7832. Callback for menu item in Project context menu.
  7833. :return: None
  7834. """
  7835. self.report_usage("on_file_savescript")
  7836. App.log.debug("on_file_savescript()")
  7837. obj = self.collection.get_active()
  7838. if obj is None:
  7839. self.inform.emit('[WARNING_NOTCL] %s' %
  7840. _("No object selected. Please select an Script object to export."))
  7841. return
  7842. # Check for more compatible types and add as required
  7843. if not isinstance(obj, FlatCAMScript):
  7844. self.inform.emit('[ERROR_NOTCL] %s' %
  7845. _("Failed. Only Script objects can be saved as TCL Script files..."))
  7846. return
  7847. name = self.collection.get_active().options["name"]
  7848. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7849. try:
  7850. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7851. caption="Save Script source file",
  7852. directory=self.get_last_save_folder() + '/' + name,
  7853. filter=_filter)
  7854. except TypeError:
  7855. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Script source file"), filter=_filter)
  7856. filename = str(filename)
  7857. if filename == "":
  7858. self.inform.emit('[WARNING_NOTCL] %s' %
  7859. _("Save Script source file cancelled."))
  7860. return
  7861. else:
  7862. self.save_source_file(name, filename)
  7863. if self.defaults["global_open_style"] is False:
  7864. self.file_opened.emit("Script", filename)
  7865. self.file_saved.emit("Script", filename)
  7866. def on_file_savedocument(self):
  7867. """
  7868. Callback for menu item in Project context menu.
  7869. :return: None
  7870. """
  7871. self.report_usage("on_file_savedocument")
  7872. App.log.debug("on_file_savedocument()")
  7873. obj = self.collection.get_active()
  7874. if obj is None:
  7875. self.inform.emit('[WARNING_NOTCL] %s' %
  7876. _("No object selected. Please select an Document object to export."))
  7877. return
  7878. # Check for more compatible types and add as required
  7879. if not isinstance(obj, FlatCAMScript):
  7880. self.inform.emit('[ERROR_NOTCL] %s' %
  7881. _("Failed. Only Document objects can be saved as Document files..."))
  7882. return
  7883. name = self.collection.get_active().options["name"]
  7884. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  7885. try:
  7886. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7887. caption="Save Document source file",
  7888. directory=self.get_last_save_folder() + '/' + name,
  7889. filter=_filter)
  7890. except TypeError:
  7891. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Document source file"), filter=_filter)
  7892. filename = str(filename)
  7893. if filename == "":
  7894. self.inform.emit('[WARNING_NOTCL] %s' %
  7895. _("Save Document source file cancelled."))
  7896. return
  7897. else:
  7898. self.save_source_file(name, filename)
  7899. if self.defaults["global_open_style"] is False:
  7900. self.file_opened.emit("Document", filename)
  7901. self.file_saved.emit("Document", filename)
  7902. def on_file_saveexcellon(self):
  7903. """
  7904. Callback for menu item in project context menu.
  7905. :return: None
  7906. """
  7907. self.report_usage("on_file_saveexcellon")
  7908. App.log.debug("on_file_saveexcellon()")
  7909. obj = self.collection.get_active()
  7910. if obj is None:
  7911. self.inform.emit('[WARNING_NOTCL] %s' %
  7912. _("No object selected. Please select an Excellon object to export."))
  7913. return
  7914. # Check for more compatible types and add as required
  7915. if not isinstance(obj, FlatCAMExcellon):
  7916. self.inform.emit('[ERROR_NOTCL] %s' %
  7917. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7918. return
  7919. name = self.collection.get_active().options["name"]
  7920. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7921. try:
  7922. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7923. caption=_("Save Excellon source file"),
  7924. directory=self.get_last_save_folder() + '/' + name,
  7925. filter=_filter)
  7926. except TypeError:
  7927. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  7928. filename = str(filename)
  7929. if filename == "":
  7930. self.inform.emit('[WARNING_NOTCL] %s' %
  7931. _("Saving Excellon source file cancelled."))
  7932. return
  7933. else:
  7934. self.save_source_file(name, filename)
  7935. if self.defaults["global_open_style"] is False:
  7936. self.file_opened.emit("Excellon", filename)
  7937. self.file_saved.emit("Excellon", filename)
  7938. def on_file_exportexcellon(self):
  7939. """
  7940. Callback for menu item File->Export->Excellon.
  7941. :return: None
  7942. """
  7943. self.report_usage("on_file_exportexcellon")
  7944. App.log.debug("on_file_exportexcellon()")
  7945. obj = self.collection.get_active()
  7946. if obj is None:
  7947. self.inform.emit('[WARNING_NOTCL] %s' %
  7948. _("No object selected. Please Select an Excellon object to export."))
  7949. return
  7950. # Check for more compatible types and add as required
  7951. if not isinstance(obj, FlatCAMExcellon):
  7952. self.inform.emit('[ERROR_NOTCL] %s' %
  7953. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7954. return
  7955. name = self.collection.get_active().options["name"]
  7956. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7957. try:
  7958. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7959. caption=_("Export Excellon"),
  7960. directory=self.get_last_save_folder() + '/' + name,
  7961. filter=_filter)
  7962. except TypeError:
  7963. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  7964. filename = str(filename)
  7965. if filename == "":
  7966. self.inform.emit('[WARNING_NOTCL] %s' %
  7967. _("Export Excellon cancelled."))
  7968. return
  7969. else:
  7970. self.export_excellon(name, filename)
  7971. if self.defaults["global_open_style"] is False:
  7972. self.file_opened.emit("Excellon", filename)
  7973. self.file_saved.emit("Excellon", filename)
  7974. def on_file_exportgerber(self):
  7975. """
  7976. Callback for menu item File->Export->Gerber.
  7977. :return: None
  7978. """
  7979. self.report_usage("on_file_exportgerber")
  7980. App.log.debug("on_file_exportgerber()")
  7981. obj = self.collection.get_active()
  7982. if obj is None:
  7983. self.inform.emit('[WARNING_NOTCL] %s' %
  7984. _("No object selected. Please Select an Gerber object to export."))
  7985. return
  7986. # Check for more compatible types and add as required
  7987. if not isinstance(obj, FlatCAMGerber):
  7988. self.inform.emit('[ERROR_NOTCL] %s' %
  7989. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7990. return
  7991. name = self.collection.get_active().options["name"]
  7992. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  7993. try:
  7994. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7995. caption=_("Export Gerber"),
  7996. directory=self.get_last_save_folder() + '/' + name,
  7997. filter=_filter_)
  7998. except TypeError:
  7999. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  8000. filename = str(filename)
  8001. if filename == "":
  8002. self.inform.emit('[WARNING_NOTCL] %s' %
  8003. _("Export Gerber cancelled."))
  8004. return
  8005. else:
  8006. self.export_gerber(name, filename)
  8007. if self.defaults["global_open_style"] is False:
  8008. self.file_opened.emit("Gerber", filename)
  8009. self.file_saved.emit("Gerber", filename)
  8010. def on_file_exportdxf(self):
  8011. """
  8012. Callback for menu item File->Export DXF.
  8013. :return: None
  8014. """
  8015. self.report_usage("on_file_exportdxf")
  8016. App.log.debug("on_file_exportdxf()")
  8017. obj = self.collection.get_active()
  8018. if obj is None:
  8019. self.inform.emit('[WARNING_NOTCL] %s' %
  8020. _("No object selected."))
  8021. msg = _("Please Select a Geometry object to export")
  8022. msgbox = QtWidgets.QMessageBox()
  8023. msgbox.setInformativeText(msg)
  8024. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8025. msgbox.setDefaultButton(bt_ok)
  8026. msgbox.exec_()
  8027. return
  8028. # Check for more compatible types and add as required
  8029. if not isinstance(obj, FlatCAMGeometry):
  8030. msg = '[ERROR_NOTCL] %s' % \
  8031. _("Only Geometry objects can be used.")
  8032. msgbox = QtWidgets.QMessageBox()
  8033. msgbox.setInformativeText(msg)
  8034. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8035. msgbox.setDefaultButton(bt_ok)
  8036. msgbox.exec_()
  8037. return
  8038. name = self.collection.get_active().options["name"]
  8039. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  8040. try:
  8041. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8042. caption=_("Export DXF"),
  8043. directory=self.get_last_save_folder() + '/' + name,
  8044. filter=_filter_)
  8045. except TypeError:
  8046. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  8047. filter=_filter_)
  8048. filename = str(filename)
  8049. if filename == "":
  8050. self.inform.emit('[WARNING_NOTCL] %s' %
  8051. _("Export DXF cancelled."))
  8052. return
  8053. else:
  8054. self.export_dxf(name, filename)
  8055. if self.defaults["global_open_style"] is False:
  8056. self.file_opened.emit("DXF", filename)
  8057. self.file_saved.emit("DXF", filename)
  8058. def on_file_importsvg(self, type_of_obj):
  8059. """
  8060. Callback for menu item File->Import SVG.
  8061. :param type_of_obj: to import the SVG as Geometry or as Gerber
  8062. :type type_of_obj: str
  8063. :return: None
  8064. """
  8065. self.report_usage("on_file_importsvg")
  8066. App.log.debug("on_file_importsvg()")
  8067. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  8068. try:
  8069. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  8070. directory=self.get_last_folder(), filter=_filter_)
  8071. except TypeError:
  8072. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  8073. filter=_filter_)
  8074. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  8075. type_of_obj = "geometry"
  8076. filenames = [str(filename) for filename in filenames]
  8077. if len(filenames) == 0:
  8078. self.inform.emit('[WARNING_NOTCL] %s' %
  8079. _("Open SVG cancelled."))
  8080. else:
  8081. for filename in filenames:
  8082. if filename != '':
  8083. self.worker_task.emit({'fcn': self.import_svg,
  8084. 'params': [filename, type_of_obj]})
  8085. def on_file_importdxf(self, type_of_obj):
  8086. """
  8087. Callback for menu item File->Import DXF.
  8088. :param type_of_obj: to import the DXF as Geometry or as Gerber
  8089. :type type_of_obj: str
  8090. :return: None
  8091. """
  8092. self.report_usage("on_file_importdxf")
  8093. App.log.debug("on_file_importdxf()")
  8094. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  8095. try:
  8096. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  8097. directory=self.get_last_folder(),
  8098. filter=_filter_)
  8099. except TypeError:
  8100. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  8101. filter=_filter_)
  8102. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  8103. type_of_obj = "geometry"
  8104. filenames = [str(filename) for filename in filenames]
  8105. if len(filenames) == 0:
  8106. self.inform.emit('[WARNING_NOTCL] %s' %
  8107. _("Open DXF cancelled."))
  8108. else:
  8109. for filename in filenames:
  8110. if filename != '':
  8111. self.worker_task.emit({'fcn': self.import_dxf,
  8112. 'params': [filename, type_of_obj]})
  8113. # ###############################################################################################################
  8114. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  8115. # ###############################################################################################################
  8116. def init_code_editor(self, name):
  8117. self.text_editor_tab = TextEditor(app=self)
  8118. # add the tab if it was closed
  8119. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  8120. self.text_editor_tab.setObjectName('text_editor_tab')
  8121. # delete the absolute and relative position and messages in the infobar
  8122. self.ui.position_label.setText("")
  8123. self.ui.rel_position_label.setText("")
  8124. # first clear previous text in text editor (if any)
  8125. self.text_editor_tab.code_editor.clear()
  8126. self.text_editor_tab.code_editor.setReadOnly(False)
  8127. self.toggle_codeeditor = True
  8128. self.text_editor_tab.code_editor.completer_enable = False
  8129. self.text_editor_tab.buttonRun.hide()
  8130. # make sure to keep a reference to the code editor
  8131. self.reference_code_editor = self.text_editor_tab.code_editor
  8132. # Switch plot_area to CNCJob tab
  8133. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  8134. def on_view_source(self):
  8135. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  8136. self.proc_container.view.set_busy(_("Loading..."))
  8137. try:
  8138. obj = self.collection.get_active()
  8139. except Exception as e:
  8140. log.debug("App.on_view_source() --> %s" % str(e))
  8141. self.inform.emit('[WARNING_NOTCL] %s' %
  8142. _("Select an Gerber or Excellon file to view it's source file."))
  8143. return 'fail'
  8144. if obj is None:
  8145. self.inform.emit('[WARNING_NOTCL] %s' %
  8146. _("Select an Gerber or Excellon file to view it's source file."))
  8147. return 'fail'
  8148. flt = "All Files (*.*)"
  8149. if obj.kind == 'gerber':
  8150. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  8151. elif obj.kind == 'excellon':
  8152. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  8153. elif obj.kind == 'cncjob':
  8154. "GCode Files (*.NC);;All Files (*.*)"
  8155. self.source_editor_tab = TextEditor(app=self)
  8156. # add the tab if it was closed
  8157. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  8158. self.source_editor_tab.setObjectName('source_editor_tab')
  8159. # delete the absolute and relative position and messages in the infobar
  8160. self.ui.position_label.setText("")
  8161. self.ui.rel_position_label.setText("")
  8162. # first clear previous text in text editor (if any)
  8163. self.source_editor_tab.code_editor.clear()
  8164. self.source_editor_tab.code_editor.setReadOnly(False)
  8165. self.source_editor_tab.code_editor.completer_enable = False
  8166. self.source_editor_tab.buttonRun.hide()
  8167. # Switch plot_area to CNCJob tab
  8168. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  8169. try:
  8170. self.source_editor_tab.buttonOpen.clicked.disconnect()
  8171. except TypeError:
  8172. pass
  8173. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  8174. try:
  8175. self.source_editor_tab.buttonSave.clicked.disconnect()
  8176. except TypeError:
  8177. pass
  8178. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  8179. # then append the text from GCode to the text editor
  8180. if obj.kind == 'cncjob':
  8181. try:
  8182. file = obj.export_gcode(
  8183. preamble=self.defaults["cncjob_prepend"],
  8184. postamble=self.defaults["cncjob_append"],
  8185. to_file=True)
  8186. if file == 'fail':
  8187. return 'fail'
  8188. except AttributeError:
  8189. self.inform.emit('[WARNING_NOTCL] %s' %
  8190. _("There is no selected object for which to see it's source file code."))
  8191. return 'fail'
  8192. else:
  8193. try:
  8194. file = StringIO(obj.source_file)
  8195. except AttributeError:
  8196. self.inform.emit('[WARNING_NOTCL] %s' %
  8197. _("There is no selected object for which to see it's source file code."))
  8198. return 'fail'
  8199. self.source_editor_tab.t_frame.hide()
  8200. try:
  8201. for line in file:
  8202. QtWidgets.QApplication.processEvents()
  8203. proc_line = str(line).strip('\n')
  8204. self.source_editor_tab.code_editor.append(proc_line)
  8205. except Exception as e:
  8206. log.debug('App.on_view_source() -->%s' % str(e))
  8207. self.inform.emit('[ERROR] %s: %s' %
  8208. (_('Failed to load the source code for the selected object'), str(e)))
  8209. return
  8210. self.source_editor_tab.handleTextChanged()
  8211. self.source_editor_tab.t_frame.show()
  8212. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  8213. self.proc_container.view.set_idle()
  8214. # self.ui.show()
  8215. def on_toggle_code_editor(self):
  8216. self.report_usage("on_toggle_code_editor()")
  8217. if self.toggle_codeeditor is False:
  8218. self.init_code_editor(name=_("Code Editor"))
  8219. self.text_editor_tab.buttonOpen.clicked.disconnect()
  8220. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  8221. self.text_editor_tab.buttonSave.clicked.disconnect()
  8222. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  8223. else:
  8224. for idx in range(self.ui.plot_tab_area.count()):
  8225. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  8226. self.ui.plot_tab_area.closeTab(idx)
  8227. break
  8228. self.toggle_codeeditor = False
  8229. def on_code_editor_close(self):
  8230. print("closed")
  8231. self.toggle_codeeditor = False
  8232. def on_filenewscript(self, silent=False, name=None, text=None):
  8233. """
  8234. Will create a new script file and open it in the Code Editor
  8235. :param silent: if True will not display status messages
  8236. :return: None
  8237. """
  8238. if silent is False:
  8239. self.inform.emit('[success] %s' %
  8240. _("New TCL script file created in Code Editor."))
  8241. # delete the absolute and relative position and messages in the infobar
  8242. self.ui.position_label.setText("")
  8243. self.ui.rel_position_label.setText("")
  8244. if name is not None:
  8245. self.new_script_object(name=name, text=text)
  8246. else:
  8247. self.new_script_object(text=text)
  8248. # script_text = script_obj.source_file
  8249. #
  8250. # self.proc_container.view.set_busy(_("Loading..."))
  8251. # script_obj.script_editor_tab.t_frame.hide()
  8252. #
  8253. # script_obj.script_editor_tab.t_frame.show()
  8254. # self.proc_container.view.set_idle()
  8255. def on_fileopenscript(self, name=None, silent=False):
  8256. """
  8257. Will open a Tcl script file into the Code Editor
  8258. :param silent: if True will not display status messages
  8259. :param name: name of a Tcl script file to open
  8260. :return:
  8261. """
  8262. self.report_usage("on_fileopenscript")
  8263. App.log.debug("on_fileopenscript()")
  8264. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  8265. if name:
  8266. filenames = [name]
  8267. else:
  8268. try:
  8269. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  8270. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  8271. except TypeError:
  8272. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  8273. if len(filenames) == 0:
  8274. if silent is False:
  8275. self.inform.emit('[WARNING_NOTCL] %s' % _("Open TCL script cancelled."))
  8276. else:
  8277. for filename in filenames:
  8278. if filename != '':
  8279. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  8280. def on_filerunscript(self, name=None, silent=False):
  8281. """
  8282. File menu callback for loading and running a TCL script.
  8283. :param silent: if True will not display status messages
  8284. :param name: name of a Tcl script file to be run by FlatCAM
  8285. :return: None
  8286. """
  8287. self.report_usage("on_filerunscript")
  8288. App.log.debug("on_file_runscript()")
  8289. if name:
  8290. filename = name
  8291. if self.cmd_line_headless != 1:
  8292. self.splash.showMessage('%s: %ssec\n%s' %
  8293. (_("Canvas initialization started.\n"
  8294. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8295. _("Executing FlatCAMScript file.")
  8296. ),
  8297. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8298. color=QtGui.QColor("gray"))
  8299. else:
  8300. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  8301. try:
  8302. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  8303. directory=self.get_last_folder(), filter=_filter_)
  8304. except TypeError:
  8305. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  8306. # The Qt methods above will return a QString which can cause problems later.
  8307. # So far json.dump() will fail to serialize it.
  8308. # TODO: Improve the serialization methods and remove this fix.
  8309. filename = str(filename)
  8310. if filename == "":
  8311. if silent is False:
  8312. self.inform.emit('[WARNING_NOTCL] %s' %
  8313. _("Run TCL script cancelled."))
  8314. else:
  8315. if self.cmd_line_headless != 1:
  8316. if self.ui.shell_dock.isHidden():
  8317. self.ui.shell_dock.show()
  8318. try:
  8319. with open(filename, "r") as tcl_script:
  8320. cmd_line_shellfile_content = tcl_script.read()
  8321. if self.cmd_line_headless != 1:
  8322. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  8323. else:
  8324. self.shell._sysShell.exec_command(cmd_line_shellfile_content, no_echo=True)
  8325. if silent is False:
  8326. self.inform.emit('[success] %s' %
  8327. _("TCL script file opened in Code Editor and executed."))
  8328. except Exception as e:
  8329. log.debug("App.on_filerunscript() -> %s" % str(e))
  8330. sys.exit(2)
  8331. def on_file_saveproject(self, silent=False):
  8332. """
  8333. Callback for menu item File->Save Project. Saves the project to
  8334. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  8335. if set to None. The project is saved by calling ``self.save_project()``.
  8336. :param silent: if True will not display status messages
  8337. :return: None
  8338. """
  8339. self.report_usage("on_file_saveproject")
  8340. if self.project_filename is None:
  8341. self.on_file_saveprojectas()
  8342. else:
  8343. self.worker_task.emit({'fcn': self.save_project,
  8344. 'params': [self.project_filename, silent]})
  8345. if self.defaults["global_open_style"] is False:
  8346. self.file_opened.emit("project", self.project_filename)
  8347. self.file_saved.emit("project", self.project_filename)
  8348. self.set_ui_title(name=self.project_filename)
  8349. self.should_we_save = False
  8350. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  8351. """
  8352. Callback for menu item File->Save Project As... Opens a file
  8353. chooser and saves the project to the given file via
  8354. ``self.save_project()``.
  8355. :param make_copy if to be create a copy of the project; boolean
  8356. :param use_thread: if to be run in a separate thread; boolean
  8357. :param quit_action: if to be followed by quiting the application; boolean
  8358. :return: None
  8359. """
  8360. self.report_usage("on_file_saveprojectas")
  8361. self.date = str(datetime.today()).rpartition('.')[0]
  8362. self.date = ''.join(c for c in self.date if c not in ':-')
  8363. self.date = self.date.replace(' ', '_')
  8364. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  8365. try:
  8366. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8367. caption=_("Save Project As ..."),
  8368. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  8369. filter=filter_)
  8370. except TypeError:
  8371. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  8372. filename = str(filename)
  8373. if filename == '':
  8374. self.inform.emit('[WARNING_NOTCL] %s' %
  8375. _("Save Project cancelled."))
  8376. return
  8377. try:
  8378. f = open(filename, 'r')
  8379. f.close()
  8380. except IOError:
  8381. pass
  8382. if use_thread is True:
  8383. self.worker_task.emit({'fcn': self.save_project,
  8384. 'params': [filename, quit_action]})
  8385. else:
  8386. self.save_project(filename, quit_action)
  8387. # self.save_project(filename)
  8388. if self.defaults["global_open_style"] is False:
  8389. self.file_opened.emit("project", filename)
  8390. self.file_saved.emit("project", filename)
  8391. if not make_copy:
  8392. self.project_filename = filename
  8393. self.set_ui_title(name=self.project_filename)
  8394. self.should_we_save = False
  8395. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  8396. """
  8397. Exports a Geometry Object to an SVG file.
  8398. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8399. :param filename: Path to the SVG file to save to.
  8400. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  8401. :return:
  8402. """
  8403. self.report_usage("export_svg()")
  8404. if filename is None:
  8405. filename = self.defaults["global_last_save_folder"]
  8406. self.log.debug("export_svg()")
  8407. try:
  8408. obj = self.collection.get_by_name(str(obj_name))
  8409. except:
  8410. # TODO: The return behavior has not been established... should raise exception?
  8411. return "Could not retrieve object: %s" % obj_name
  8412. with self.proc_container.new(_("Exporting SVG")) as proc:
  8413. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  8414. # Determine bounding area for svg export
  8415. bounds = obj.bounds()
  8416. size = obj.size()
  8417. # Convert everything to strings for use in the xml doc
  8418. svgwidth = str(size[0])
  8419. svgheight = str(size[1])
  8420. minx = str(bounds[0])
  8421. miny = str(bounds[1] - size[1])
  8422. uom = obj.units.lower()
  8423. # Add a SVG Header and footer to the svg output from shapely
  8424. # The transform flips the Y Axis so that everything renders
  8425. # properly within svg apps such as inkscape
  8426. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8427. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8428. svg_header += 'width="' + svgwidth + uom + '" '
  8429. svg_header += 'height="' + svgheight + uom + '" '
  8430. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  8431. svg_header += '<g transform="scale(1,-1)">'
  8432. svg_footer = '</g> </svg>'
  8433. svg_elem = svg_header + exported_svg + svg_footer
  8434. # Parse the xml through a xml parser just to add line feeds
  8435. # and to make it look more pretty for the output
  8436. svgcode = parse_xml_string(svg_elem)
  8437. svgcode = svgcode.toprettyxml()
  8438. try:
  8439. with open(filename, 'w') as fp:
  8440. fp.write(svgcode)
  8441. except PermissionError:
  8442. self.inform.emit('[WARNING] %s' %
  8443. _("Permission denied, saving not possible.\n"
  8444. "Most likely another app is holding the file open and not accessible."))
  8445. return 'fail'
  8446. if self.defaults["global_open_style"] is False:
  8447. self.file_opened.emit("SVG", filename)
  8448. self.file_saved.emit("SVG", filename)
  8449. self.inform.emit('[success] %s: %s' %
  8450. (_("SVG file exported to"), filename))
  8451. def export_svg_negative(self, obj_name, box_name, filename, boundary,
  8452. scale_stroke_factor=0.00,
  8453. scale_factor_x=None, scale_factor_y=None,
  8454. skew_factor_x=None, skew_factor_y=None, skew_reference='center',
  8455. mirror=None,
  8456. use_thread=True):
  8457. """
  8458. Exports a Geometry Object to an SVG file in negative.
  8459. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8460. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  8461. :param filename: Path to the SVG file to save to.
  8462. :param boundary: thickness of a black border to surround all the features
  8463. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  8464. :param scale_factor_x: factor to scale the svg geometry on the X axis
  8465. :param scale_factor_y: factor to scale the svg geometry on the Y axis
  8466. :param skew_factor_x: factor to skew the svg geometry on the X axis
  8467. :param skew_factor_y: factor to skew the svg geometry on the Y axis
  8468. :param skew_reference: reference to use for skew. Can be 'bottomleft', 'bottomright', 'topleft', 'topright' and
  8469. those are the 4 points of the bounding box of the geometry to be skewed.
  8470. :param mirror: can be 'x' or 'y' or 'both'. Axis on which to mirror the svg geometry
  8471. :param use_thread: if to be run in a separate thread; boolean
  8472. :return:
  8473. """
  8474. self.report_usage("export_negative()")
  8475. if filename is None:
  8476. filename = self.defaults["global_last_save_folder"]
  8477. self.log.debug("export_svg() negative")
  8478. try:
  8479. obj = self.collection.get_by_name(str(obj_name))
  8480. except:
  8481. # TODO: The return behavior has not been established... should raise exception?
  8482. return "Could not retrieve object: %s" % obj_name
  8483. try:
  8484. box = self.collection.get_by_name(str(box_name))
  8485. except:
  8486. # TODO: The return behavior has not been established... should raise exception?
  8487. return "Could not retrieve object: %s" % box_name
  8488. if box is None:
  8489. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  8490. (_("No object Box. Using instead"), obj))
  8491. box = obj
  8492. def make_negative_film():
  8493. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor,
  8494. scale_factor_x=scale_factor_x, scale_factor_y=scale_factor_y,
  8495. skew_factor_x=skew_factor_x, skew_factor_y=skew_factor_y,
  8496. mirror=mirror
  8497. )
  8498. # Determine bounding area for svg export
  8499. bounds = box.bounds()
  8500. size = box.size()
  8501. uom = obj.units.lower()
  8502. # Convert everything to strings for use in the xml doc
  8503. svgwidth = str(size[0] + (2 * boundary))
  8504. svgheight = str(size[1] + (2 * boundary))
  8505. minx = str(bounds[0] - boundary)
  8506. miny = str(bounds[1] + boundary + size[1])
  8507. miny_rect = str(bounds[1] - boundary)
  8508. # Add a SVG Header and footer to the svg output from shapely
  8509. # The transform flips the Y Axis so that everything renders
  8510. # properly within svg apps such as inkscape
  8511. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8512. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8513. svg_header += 'width="' + svgwidth + uom + '" '
  8514. svg_header += 'height="' + svgheight + uom + '" '
  8515. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  8516. svg_header += '>'
  8517. svg_header += '<g transform="scale(1,-1)">'
  8518. svg_footer = '</g> </svg>'
  8519. # Change the attributes of the exported SVG
  8520. # We don't need stroke-width - wrong, we do when we have lines with certain width
  8521. # We set opacity to maximum
  8522. # We set the color to WHITE
  8523. root = ET.fromstring(exported_svg)
  8524. for child in root:
  8525. child.set('fill', '#FFFFFF')
  8526. child.set('opacity', '1.0')
  8527. child.set('stroke', '#FFFFFF')
  8528. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  8529. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  8530. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  8531. first_svg_elem_tag = 'rect'
  8532. first_svg_elem_attribs = {
  8533. 'x': minx,
  8534. 'y': miny_rect,
  8535. 'width': svgwidth,
  8536. 'height': svgheight,
  8537. 'id': 'neg_rect',
  8538. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  8539. }
  8540. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  8541. exported_svg = ET.tostring(root)
  8542. svg_elem = svg_header + str(exported_svg) + svg_footer
  8543. # Parse the xml through a xml parser just to add line feeds
  8544. # and to make it look more pretty for the output
  8545. doc = parse_xml_string(svg_elem)
  8546. try:
  8547. with open(filename, 'w') as fp:
  8548. fp.write(doc.toprettyxml())
  8549. except PermissionError:
  8550. self.inform.emit('[WARNING] %s' %
  8551. _("Permission denied, saving not possible.\n"
  8552. "Most likely another app is holding the file open and not accessible."))
  8553. return 'fail'
  8554. if self.defaults["global_open_style"] is False:
  8555. self.file_opened.emit("SVG", filename)
  8556. self.file_saved.emit("SVG", filename)
  8557. self.inform.emit('[success] %s: %s' %
  8558. (_("SVG file exported to"), filename))
  8559. if use_thread is True:
  8560. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  8561. def job_thread_film(app_obj):
  8562. try:
  8563. make_negative_film()
  8564. except Exception as e:
  8565. proc.done()
  8566. return
  8567. proc.done()
  8568. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  8569. else:
  8570. make_negative_film()
  8571. def export_svg_positive(self, obj_name, box_name, filename,
  8572. scale_stroke_factor=0.00,
  8573. scale_factor_x=None, scale_factor_y=None,
  8574. skew_factor_x=None, skew_factor_y=None, skew_reference='center',
  8575. mirror=None,
  8576. use_thread=True):
  8577. """
  8578. Exports a Geometry Object to an SVG file in positive black.
  8579. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8580. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  8581. :param filename: Path to the SVG file to save to.
  8582. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  8583. :param scale_factor_x: factor to scale the svg geometry on the X axis
  8584. :param scale_factor_y: factor to scale the svg geometry on the Y axis
  8585. :param skew_factor_x: factor to skew the svg geometry on the X axis
  8586. :param skew_factor_y: factor to skew the svg geometry on the Y axis
  8587. :param skew_reference: reference to use for skew. Can be 'bottomleft', 'bottomright', 'topleft', 'topright' and
  8588. those are the 4 points of the bounding box of the geometry to be skewed.
  8589. :param mirror: can be 'x' or 'y' or 'both'. Axis on which to mirror the svg geometry
  8590. :param use_thread: if to be run in a separate thread; boolean
  8591. :return:
  8592. """
  8593. self.report_usage("export_svg_positive()")
  8594. if filename is None:
  8595. filename = self.defaults["global_last_save_folder"]
  8596. self.log.debug("export_svg() black")
  8597. try:
  8598. obj = self.collection.get_by_name(str(obj_name))
  8599. except:
  8600. # TODO: The return behavior has not been established... should raise exception?
  8601. return "Could not retrieve object: %s" % obj_name
  8602. try:
  8603. box = self.collection.get_by_name(str(box_name))
  8604. except:
  8605. # TODO: The return behavior has not been established... should raise exception?
  8606. return "Could not retrieve object: %s" % box_name
  8607. if box is None:
  8608. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  8609. (_("No object Box. Using instead"), obj))
  8610. box = obj
  8611. def make_positive_film():
  8612. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor,
  8613. scale_factor_x=scale_factor_x, scale_factor_y=scale_factor_y,
  8614. skew_factor_x=skew_factor_x, skew_factor_y=skew_factor_y,
  8615. mirror=mirror
  8616. )
  8617. self.progress.emit(40)
  8618. # Change the attributes of the exported SVG
  8619. # We don't need stroke-width
  8620. # We set opacity to maximum
  8621. # We set the colour to WHITE
  8622. root = ET.fromstring(exported_svg)
  8623. for child in root:
  8624. child.set('fill', str(self.defaults['tools_film_color']))
  8625. child.set('opacity', '1.0')
  8626. child.set('stroke', str(self.defaults['tools_film_color']))
  8627. exported_svg = ET.tostring(root)
  8628. # Determine bounding area for svg export
  8629. bounds = box.bounds()
  8630. size = box.size()
  8631. # This contain the measure units
  8632. uom = obj.units.lower()
  8633. # Define a boundary around SVG of about 1.0mm (~39mils)
  8634. if uom in "mm":
  8635. boundary = 1.0
  8636. else:
  8637. boundary = 0.0393701
  8638. self.progress.emit(80)
  8639. # Convert everything to strings for use in the xml doc
  8640. svgwidth = str(size[0] + (2 * boundary))
  8641. svgheight = str(size[1] + (2 * boundary))
  8642. minx = str(bounds[0] - boundary)
  8643. miny = str(bounds[1] + boundary + size[1])
  8644. self.log.debug(minx)
  8645. self.log.debug(miny)
  8646. # Add a SVG Header and footer to the svg output from shapely
  8647. # The transform flips the Y Axis so that everything renders
  8648. # properly within svg apps such as inkscape
  8649. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8650. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8651. svg_header += 'width="' + svgwidth + uom + '" '
  8652. svg_header += 'height="' + svgheight + uom + '" '
  8653. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  8654. svg_header += '>'
  8655. svg_header += '<g transform="scale(1,-1)">'
  8656. svg_footer = '</g> </svg>'
  8657. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  8658. self.progress.emit(90)
  8659. # Parse the xml through a xml parser just to add line feeds
  8660. # and to make it look more pretty for the output
  8661. doc = parse_xml_string(svg_elem)
  8662. try:
  8663. with open(filename, 'w') as fp:
  8664. fp.write(doc.toprettyxml())
  8665. except PermissionError:
  8666. self.inform.emit('[WARNING] %s' %
  8667. _("Permission denied, saving not possible.\n"
  8668. "Most likely another app is holding the file open and not accessible."))
  8669. return 'fail'
  8670. self.progress.emit(100)
  8671. if self.defaults["global_open_style"] is False:
  8672. self.file_opened.emit("SVG", filename)
  8673. self.file_saved.emit("SVG", filename)
  8674. self.inform.emit('[success] %s: %s' %
  8675. (_("SVG file exported to"), filename))
  8676. if use_thread is True:
  8677. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  8678. def job_thread_film(app_obj):
  8679. try:
  8680. make_positive_film()
  8681. except Exception as e:
  8682. proc.done()
  8683. return
  8684. proc.done()
  8685. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  8686. else:
  8687. make_positive_film()
  8688. def save_source_file(self, obj_name, filename, use_thread=True):
  8689. """
  8690. Exports a FlatCAM Object to an Gerber/Excellon file.
  8691. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8692. :param filename: Path to the Gerber file to save to.
  8693. :param use_thread: if to be run in a separate thread
  8694. :return:
  8695. """
  8696. self.report_usage("save source file()")
  8697. if filename is None:
  8698. filename = self.defaults["global_last_save_folder"]
  8699. self.log.debug("save source file()")
  8700. obj = self.collection.get_by_name(obj_name)
  8701. file_string = StringIO(obj.source_file)
  8702. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8703. try:
  8704. with open(filename, 'w') as file:
  8705. file.writelines('G04*\n')
  8706. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8707. (obj.kind.upper(), str(self.version), str(self.version_date)))
  8708. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8709. file.writelines('G04 Created on : %s*\n' % time_string)
  8710. for line in file_string:
  8711. file.writelines(line)
  8712. except PermissionError:
  8713. self.inform.emit('[WARNING] %s' %
  8714. _("Permission denied, saving not possible.\n"
  8715. "Most likely another app is holding the file open and not accessible."))
  8716. return 'fail'
  8717. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  8718. """
  8719. Exports a Excellon Object to an Excellon file.
  8720. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  8721. :param filename: Path to the Excellon file to save to.
  8722. :param use_thread: if to be run in a separate thread
  8723. :return:
  8724. """
  8725. self.report_usage("export_excellon()")
  8726. if filename is None:
  8727. filename = self.defaults["global_last_save_folder"]
  8728. self.log.debug("export_excellon()")
  8729. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  8730. self.defaults["excellon_exp_decimals"]
  8731. )
  8732. if local_use is None:
  8733. try:
  8734. obj = self.collection.get_by_name(str(obj_name))
  8735. except:
  8736. # TODO: The return behavior has not been established... should raise exception?
  8737. return "Could not retrieve object: %s" % obj_name
  8738. else:
  8739. obj = local_use
  8740. # updated units
  8741. eunits = self.defaults["excellon_exp_units"]
  8742. ewhole = self.defaults["excellon_exp_integer"]
  8743. efract = self.defaults["excellon_exp_decimals"]
  8744. ezeros = self.defaults["excellon_exp_zeros"]
  8745. eformat = self.defaults["excellon_exp_format"]
  8746. slot_type = self.defaults["excellon_exp_slot_type"]
  8747. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8748. if fc_units == 'MM':
  8749. factor = 1 if eunits == 'METRIC' else 0.03937
  8750. else:
  8751. factor = 25.4 if eunits == 'METRIC' else 1
  8752. def make_excellon():
  8753. try:
  8754. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8755. header = 'M48\n'
  8756. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  8757. (str(self.version), str(self.version_date))
  8758. header += ';Filename: %s' % str(obj_name) + '\n'
  8759. header += ';Created on : %s' % time_str + '\n'
  8760. if eformat == 'dec':
  8761. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  8762. header += eunits + '\n'
  8763. for tool in obj.tools:
  8764. if eunits == 'METRIC':
  8765. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8766. tool=str(tool),
  8767. dec=2)
  8768. else:
  8769. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8770. tool=str(tool),
  8771. dec=4)
  8772. else:
  8773. if ezeros == 'LZ':
  8774. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8775. form='ndec', e_zeros='LZ', factor=factor,
  8776. slot_type=slot_type)
  8777. header += '%s,%s\n' % (eunits, 'LZ')
  8778. header += format_exc
  8779. for tool in obj.tools:
  8780. if eunits == 'METRIC':
  8781. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8782. tool=str(tool),
  8783. dec=2)
  8784. else:
  8785. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8786. tool=str(tool),
  8787. dec=4)
  8788. else:
  8789. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8790. form='ndec', e_zeros='TZ', factor=factor,
  8791. slot_type=slot_type)
  8792. header += '%s,%s\n' % (eunits, 'TZ')
  8793. header += format_exc
  8794. for tool in obj.tools:
  8795. if eunits == 'METRIC':
  8796. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8797. tool=str(tool),
  8798. dec=2)
  8799. else:
  8800. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8801. tool=str(tool),
  8802. dec=4)
  8803. header += '%\n'
  8804. footer = 'M30\n'
  8805. exported_excellon = header
  8806. exported_excellon += excellon_code
  8807. exported_excellon += footer
  8808. if local_use is None:
  8809. try:
  8810. with open(filename, 'w') as fp:
  8811. fp.write(exported_excellon)
  8812. except PermissionError:
  8813. self.inform.emit('[WARNING] %s' %
  8814. _("Permission denied, saving not possible.\n"
  8815. "Most likely another app is holding the file open and not accessible."))
  8816. return 'fail'
  8817. if self.defaults["global_open_style"] is False:
  8818. self.file_opened.emit("Excellon", filename)
  8819. self.file_saved.emit("Excellon", filename)
  8820. self.inform.emit('[success] %s: %s' %
  8821. (_("Excellon file exported to"), filename))
  8822. else:
  8823. return exported_excellon
  8824. except Exception as e:
  8825. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  8826. return 'fail'
  8827. if use_thread is True:
  8828. with self.proc_container.new(_("Exporting Excellon")) as proc:
  8829. def job_thread_exc(app_obj):
  8830. ret = make_excellon()
  8831. if ret == 'fail':
  8832. self.inform.emit('[ERROR_NOTCL] %s' %
  8833. _('Could not export Excellon file.'))
  8834. return
  8835. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8836. else:
  8837. ret = make_excellon()
  8838. if ret == 'fail':
  8839. self.inform.emit('[ERROR_NOTCL] %s' %
  8840. _('Could not export Excellon file.'))
  8841. return 'fail'
  8842. if local_use is not None:
  8843. return ret
  8844. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  8845. """
  8846. Exports a Gerber Object to an Gerber file.
  8847. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  8848. :param filename: Path to the Gerber file to save to.
  8849. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8850. When not None, the value will be the actual Gerber object for which to create the Gerber code
  8851. :param use_thread: if to be run in a separate thread
  8852. :return:
  8853. """
  8854. self.report_usage("export_gerber()")
  8855. if filename is None:
  8856. filename = self.defaults["global_last_save_folder"]
  8857. self.log.debug("export_gerber()")
  8858. if local_use is None:
  8859. try:
  8860. obj = self.collection.get_by_name(str(obj_name))
  8861. except:
  8862. # TODO: The return behavior has not been established... should raise exception?
  8863. return "Could not retrieve object: %s" % obj_name
  8864. else:
  8865. obj = local_use
  8866. # updated units
  8867. gunits = self.defaults["gerber_exp_units"]
  8868. gwhole = self.defaults["gerber_exp_integer"]
  8869. gfract = self.defaults["gerber_exp_decimals"]
  8870. gzeros = self.defaults["gerber_exp_zeros"]
  8871. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8872. if fc_units == 'MM':
  8873. factor = 1 if gunits == 'MM' else 0.03937
  8874. else:
  8875. factor = 25.4 if gunits == 'MM' else 1
  8876. def make_gerber():
  8877. try:
  8878. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8879. header = 'G04*\n'
  8880. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  8881. (str(self.version), str(self.version_date))
  8882. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  8883. header += 'G04 Created on : %s*' % time_str + '\n'
  8884. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  8885. header += "%MO{units}*%\n".format(units=gunits)
  8886. for apid in obj.apertures:
  8887. if obj.apertures[apid]['type'] == 'C':
  8888. header += "%ADD{apid}{type},{size}*%\n".format(
  8889. apid=str(apid),
  8890. type='C',
  8891. size=(factor * obj.apertures[apid]['size'])
  8892. )
  8893. elif obj.apertures[apid]['type'] == 'R':
  8894. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8895. apid=str(apid),
  8896. type='R',
  8897. width=(factor * obj.apertures[apid]['width']),
  8898. height=(factor * obj.apertures[apid]['height'])
  8899. )
  8900. elif obj.apertures[apid]['type'] == 'O':
  8901. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8902. apid=str(apid),
  8903. type='O',
  8904. width=(factor * obj.apertures[apid]['width']),
  8905. height=(factor * obj.apertures[apid]['height'])
  8906. )
  8907. header += '\n'
  8908. # obsolete units but some software may need it
  8909. if gunits == 'IN':
  8910. header += 'G70*\n'
  8911. else:
  8912. header += 'G71*\n'
  8913. # Absolute Mode
  8914. header += 'G90*\n'
  8915. header += 'G01*\n'
  8916. # positive polarity
  8917. header += '%LPD*%\n'
  8918. footer = 'M02*\n'
  8919. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8920. exported_gerber = header
  8921. exported_gerber += gerber_code
  8922. exported_gerber += footer
  8923. if local_use is None:
  8924. try:
  8925. with open(filename, 'w') as fp:
  8926. fp.write(exported_gerber)
  8927. except PermissionError:
  8928. self.inform.emit('[WARNING] %s' %
  8929. _("Permission denied, saving not possible.\n"
  8930. "Most likely another app is holding the file open and not accessible."))
  8931. return 'fail'
  8932. if self.defaults["global_open_style"] is False:
  8933. self.file_opened.emit("Gerber", filename)
  8934. self.file_saved.emit("Gerber", filename)
  8935. self.inform.emit('[success] %s: %s' %
  8936. (_("Gerber file exported to"), filename))
  8937. else:
  8938. return exported_gerber
  8939. except Exception as e:
  8940. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8941. return 'fail'
  8942. if use_thread is True:
  8943. with self.proc_container.new(_("Exporting Gerber")) as proc:
  8944. def job_thread_grb(app_obj):
  8945. ret = make_gerber()
  8946. if ret == 'fail':
  8947. self.inform.emit('[ERROR_NOTCL] %s' %
  8948. _('Could not export Gerber file.'))
  8949. return
  8950. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8951. else:
  8952. ret = make_gerber()
  8953. if ret == 'fail':
  8954. self.inform.emit('[ERROR_NOTCL] %s' %
  8955. _('Could not export Gerber file.'))
  8956. return 'fail'
  8957. if local_use is not None:
  8958. return ret
  8959. def export_dxf(self, obj_name, filename, use_thread=True):
  8960. """
  8961. Exports a Geometry Object to an DXF file.
  8962. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8963. :param filename: Path to the DXF file to save to.
  8964. :param use_thread: if to be run in a separate thread
  8965. :return:
  8966. """
  8967. self.report_usage("export_dxf()")
  8968. if filename is None:
  8969. filename = self.defaults["global_last_save_folder"]
  8970. self.log.debug("export_dxf()")
  8971. format_exc = ''
  8972. units = ''
  8973. try:
  8974. obj = self.collection.get_by_name(str(obj_name))
  8975. except:
  8976. # TODO: The return behavior has not been established... should raise exception?
  8977. return "Could not retrieve object: %s" % obj_name
  8978. # updated units
  8979. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8980. if units == 'IN' or units == 'INCH':
  8981. units = 'INCH'
  8982. elif units == 'MM' or units == 'METIRC':
  8983. units ='METRIC'
  8984. def make_dxf():
  8985. try:
  8986. dxf_code = obj.export_dxf()
  8987. dxf_code.saveas(filename)
  8988. if self.defaults["global_open_style"] is False:
  8989. self.file_opened.emit("DXF", filename)
  8990. self.file_saved.emit("DXF", filename)
  8991. self.inform.emit('[success] %s: %s' %
  8992. (_("DXF file exported to"), filename))
  8993. except:
  8994. return 'fail'
  8995. if use_thread is True:
  8996. with self.proc_container.new(_("Exporting DXF")) as proc:
  8997. def job_thread_exc(app_obj):
  8998. ret = make_dxf()
  8999. if ret == 'fail':
  9000. app_obj.inform.emit('[WARNING_NOTCL] %s' %
  9001. _('Could not export DXF file.'))
  9002. return
  9003. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  9004. else:
  9005. ret = make_dxf()
  9006. if ret == 'fail':
  9007. self.inform.emit('[WARNING_NOTCL] %s' %
  9008. _('Could not export DXF file.'))
  9009. return
  9010. def import_svg(self, filename, geo_type='geometry', outname=None):
  9011. """
  9012. Adds a new Geometry Object to the projects and populates
  9013. it with shapes extracted from the SVG file.
  9014. :param filename: Path to the SVG file.
  9015. :param geo_type: Type of FlatCAM object that will be created from SVG
  9016. :param outname:
  9017. :return:
  9018. """
  9019. self.report_usage("import_svg()")
  9020. obj_type = ""
  9021. if geo_type is None or geo_type == "geometry":
  9022. obj_type = "geometry"
  9023. elif geo_type == "gerber":
  9024. obj_type = geo_type
  9025. else:
  9026. self.inform.emit('[ERROR_NOTCL] %s' %
  9027. _("Not supported type is picked as parameter. "
  9028. "Only Geometry and Gerber are supported"))
  9029. return
  9030. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  9031. def obj_init(geo_obj, app_obj):
  9032. geo_obj.import_svg(filename, obj_type, units=units)
  9033. geo_obj.multigeo = False
  9034. with self.proc_container.new(_("Importing SVG")) as proc:
  9035. # Object name
  9036. name = outname or filename.split('/')[-1].split('\\')[-1]
  9037. self.new_object(obj_type, name, obj_init, autoselected=False)
  9038. self.progress.emit(20)
  9039. # Register recent file
  9040. self.file_opened.emit("svg", filename)
  9041. # GUI feedback
  9042. self.inform.emit('[success] %s: %s' %
  9043. (_("Opened"), filename))
  9044. self.progress.emit(100)
  9045. def import_dxf(self, filename, geo_type='geometry', outname=None):
  9046. """
  9047. Adds a new Geometry Object to the projects and populates
  9048. it with shapes extracted from the DXF file.
  9049. :param filename: Path to the DXF file.
  9050. :param geo_type: Type of FlatCAM object that will be created from DXF
  9051. :param outname:
  9052. :type putname: str
  9053. :return:
  9054. """
  9055. self.report_usage("import_dxf()")
  9056. obj_type = ""
  9057. if geo_type is None or geo_type == "geometry":
  9058. obj_type = "geometry"
  9059. elif geo_type == "gerber":
  9060. obj_type = geo_type
  9061. else:
  9062. self.inform.emit('[ERROR_NOTCL] %s' %
  9063. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  9064. return
  9065. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  9066. def obj_init(geo_obj, app_obj):
  9067. geo_obj.import_dxf(filename, obj_type, units=units)
  9068. geo_obj.multigeo = False
  9069. with self.proc_container.new(_("Importing DXF")) as proc:
  9070. # Object name
  9071. name = outname or filename.split('/')[-1].split('\\')[-1]
  9072. self.new_object(obj_type, name, obj_init, autoselected=False)
  9073. self.progress.emit(20)
  9074. # Register recent file
  9075. self.file_opened.emit("dxf", filename)
  9076. # GUI feedback
  9077. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9078. self.progress.emit(100)
  9079. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  9080. """
  9081. Adds a new Geometry Object to the projects and populates
  9082. it with shapes extracted from the SVG file.
  9083. :param filename: Path to the SVG file.
  9084. :param o_type: type of FlatCAM objeect
  9085. :param dpi: dot per inch
  9086. :param mode: black or color
  9087. :param mask: dictate the level of detail
  9088. :param outname: name for the resulting file
  9089. :return:
  9090. """
  9091. self.report_usage("import_image()")
  9092. if o_type is None or o_type == "geometry":
  9093. obj_type = "geometry"
  9094. elif o_type == "gerber":
  9095. obj_type = o_type
  9096. else:
  9097. self.inform.emit('[ERROR_NOTCL] %s' %
  9098. _("Not supported type is picked as parameter. "
  9099. "Only Geometry and Gerber are supported"))
  9100. return
  9101. def obj_init(geo_obj, app_obj):
  9102. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  9103. geo_obj.multigeo = False
  9104. with self.proc_container.new(_("Importing Image")) as proc:
  9105. # Object name
  9106. name = outname or filename.split('/')[-1].split('\\')[-1]
  9107. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  9108. self.new_object(obj_type, name, obj_init)
  9109. self.progress.emit(20)
  9110. # Register recent file
  9111. self.file_opened.emit("image", filename)
  9112. # GUI feedback
  9113. self.inform.emit('[success] %s: %s' %
  9114. (_("Opened"), filename))
  9115. self.progress.emit(100)
  9116. def open_gerber(self, filename, outname=None):
  9117. """
  9118. Opens a Gerber file, parses it and creates a new object for
  9119. it in the program. Thread-safe.
  9120. :param outname: Name of the resulting object. None causes the
  9121. name to be that of the file.
  9122. :param filename: Gerber file filename
  9123. :type filename: str
  9124. :param follow: If true, the parser will not create polygons, just lines
  9125. following the gerber path.
  9126. :type follow: bool
  9127. :return: None
  9128. """
  9129. # How the object should be initialized
  9130. def obj_init(gerber_obj, app_obj):
  9131. assert isinstance(gerber_obj, FlatCAMGerber), \
  9132. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  9133. # Opening the file happens here
  9134. self.progress.emit(30)
  9135. try:
  9136. gerber_obj.parse_file(filename)
  9137. except IOError:
  9138. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  9139. (_("Failed to open file"), filename))
  9140. app_obj.progress.emit(0)
  9141. return "fail"
  9142. except ParseError as err:
  9143. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' %
  9144. (_("Failed to parse file"), filename, str(err)))
  9145. app_obj.progress.emit(0)
  9146. self.log.error(str(err))
  9147. return "fail"
  9148. except Exception as e:
  9149. log.debug("App.open_gerber() --> %s" % str(e))
  9150. msg = '[ERROR] %s' % \
  9151. _("An internal error has occurred. See shell.\n")
  9152. msg += traceback.format_exc()
  9153. app_obj.inform.emit(msg)
  9154. return "fail"
  9155. if gerber_obj.is_empty():
  9156. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  9157. # self.collection.set_active(gerber_obj.options["name"])
  9158. # self.collection.delete_active()
  9159. self.inform.emit('[ERROR_NOTCL] %s' %
  9160. _("Object is not Gerber file or empty. Aborting object creation."))
  9161. return "fail"
  9162. # Further parsing
  9163. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  9164. App.log.debug("open_gerber()")
  9165. with self.proc_container.new(_("Opening Gerber")) as proc:
  9166. self.progress.emit(10)
  9167. # Object name
  9168. name = outname or filename.split('/')[-1].split('\\')[-1]
  9169. # # ## Object creation # ##
  9170. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  9171. if ret == 'fail':
  9172. self.inform.emit('[ERROR_NOTCL]%s' %
  9173. _(' Open Gerber failed. Probable not a Gerber file.'))
  9174. return
  9175. # Register recent file
  9176. self.file_opened.emit("gerber", filename)
  9177. self.progress.emit(100)
  9178. # GUI feedback
  9179. self.inform.emit('[success] %s: %s' %
  9180. (_("Opened"), filename))
  9181. def open_excellon(self, filename, outname=None, plot=True):
  9182. """
  9183. Opens an Excellon file, parses it and creates a new object for
  9184. it in the program. Thread-safe.
  9185. :param outname: Name of the resulting object. None causes the
  9186. name to be that of the file.
  9187. :param filename: Excellon file filename
  9188. :type filename: str
  9189. :return: None
  9190. """
  9191. App.log.debug("open_excellon()")
  9192. # How the object should be initialized
  9193. def obj_init(excellon_obj, app_obj):
  9194. # self.progress.emit(20)
  9195. try:
  9196. ret = excellon_obj.parse_file(filename=filename)
  9197. if ret == "fail":
  9198. log.debug("Excellon parsing failed.")
  9199. self.inform.emit('[ERROR_NOTCL] %s' %
  9200. _("This is not Excellon file."))
  9201. return "fail"
  9202. except IOError:
  9203. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  9204. (_("Cannot open file"), filename))
  9205. log.debug("Could not open Excellon object.")
  9206. self.progress.emit(0) # TODO: self and app_bjj mixed
  9207. return "fail"
  9208. except:
  9209. msg = '[ERROR_NOTCL] %s' % \
  9210. _("An internal error has occurred. See shell.\n")
  9211. msg += traceback.format_exc()
  9212. app_obj.inform.emit(msg)
  9213. return "fail"
  9214. ret = excellon_obj.create_geometry()
  9215. if ret == 'fail':
  9216. log.debug("Could not create geometry for Excellon object.")
  9217. return "fail"
  9218. for tool in excellon_obj.tools:
  9219. if excellon_obj.tools[tool]['solid_geometry']:
  9220. return
  9221. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  9222. (_("No geometry found in file"), filename))
  9223. return "fail"
  9224. with self.proc_container.new(_("Opening Excellon.")):
  9225. # Object name
  9226. name = outname or filename.split('/')[-1].split('\\')[-1]
  9227. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  9228. if ret_val == 'fail':
  9229. self.inform.emit('[ERROR_NOTCL] %s' %
  9230. _('Open Excellon file failed. Probable not an Excellon file.'))
  9231. return
  9232. # Register recent file
  9233. self.file_opened.emit("excellon", filename)
  9234. # GUI feedback
  9235. self.inform.emit('[success] %s: %s' %
  9236. (_("Opened"), filename))
  9237. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True):
  9238. """
  9239. Opens a G-gcode file, parses it and creates a new object for
  9240. it in the program. Thread-safe.
  9241. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9242. :param filename: G-code file filename
  9243. :type filename: str
  9244. :return: None
  9245. """
  9246. App.log.debug("open_gcode()")
  9247. # How the object should be initialized
  9248. def obj_init(job_obj, app_obj_):
  9249. """
  9250. :param job_obj: the resulting object
  9251. :type app_obj_: App
  9252. """
  9253. assert isinstance(app_obj_, App), \
  9254. "Initializer expected App, got %s" % type(app_obj_)
  9255. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  9256. try:
  9257. f = open(filename)
  9258. gcode = f.read()
  9259. f.close()
  9260. except IOError:
  9261. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  9262. (_("Failed to open"), filename))
  9263. return "fail"
  9264. job_obj.gcode = gcode
  9265. ret = job_obj.gcode_parse(force_parsing=force_parsing)
  9266. if ret == "fail":
  9267. self.inform.emit('[ERROR_NOTCL] %s' %
  9268. _("This is not GCODE"))
  9269. return "fail"
  9270. job_obj.create_geometry()
  9271. with self.proc_container.new(_("Opening G-Code.")):
  9272. # Object name
  9273. name = outname or filename.split('/')[-1].split('\\')[-1]
  9274. # New object creation and file processing
  9275. ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  9276. if ret == 'fail':
  9277. self.inform.emit('[ERROR_NOTCL] %s' %
  9278. _("Failed to create CNCJob Object. Probable not a GCode file. "
  9279. "Try to load it from File menu.\n "
  9280. "Attempting to create a FlatCAM CNCJob Object from "
  9281. "G-Code file failed during processing"))
  9282. return "fail"
  9283. # Register recent file
  9284. self.file_opened.emit("cncjob", filename)
  9285. # GUI feedback
  9286. self.inform.emit('[success] %s: %s' %
  9287. (_("Opened"), filename))
  9288. def open_script(self, filename, outname=None, silent=False):
  9289. """
  9290. Opens a Script file, parses it and creates a new object for
  9291. it in the program. Thread-safe.
  9292. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9293. :param filename: Script file filename
  9294. :type filename: str
  9295. :return: None
  9296. """
  9297. App.log.debug("open_script()")
  9298. with self.proc_container.new(_("Opening TCL Script...")):
  9299. try:
  9300. with open(filename, "r") as opened_script:
  9301. script_content = opened_script.readlines()
  9302. script_content = ''.join(script_content)
  9303. if silent is False:
  9304. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  9305. except Exception as e:
  9306. log.debug("App.open_script() -> %s" % str(e))
  9307. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to open TCL Script."))
  9308. return
  9309. # Object name
  9310. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  9311. # New object creation and file processing
  9312. self.on_filenewscript(name=script_name, text=script_content)
  9313. # Register recent file
  9314. self.file_opened.emit("script", filename)
  9315. # GUI feedback
  9316. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9317. def open_config_file(self, filename, run_from_arg=None):
  9318. """
  9319. Loads a config file from the specified file.
  9320. :param filename: Name of the file from which to load.
  9321. :type filename: str
  9322. :return: None
  9323. """
  9324. App.log.debug("Opening config file: " + filename)
  9325. if run_from_arg:
  9326. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9327. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9328. _("Opening FlatCAM Config file.")),
  9329. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9330. color=QtGui.QColor("gray"))
  9331. # add the tab if it was closed
  9332. self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  9333. # first clear previous text in text editor (if any)
  9334. self.ui.text_editor_tab.code_editor.clear()
  9335. # Switch plot_area to CNCJob tab
  9336. self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  9337. try:
  9338. if filename:
  9339. f = QtCore.QFile(filename)
  9340. if f.open(QtCore.QIODevice.ReadOnly):
  9341. stream = QtCore.QTextStream(f)
  9342. gcode_edited = stream.readAll()
  9343. self.ui.text_editor_tab.code_editor.setPlainText(gcode_edited)
  9344. f.close()
  9345. except IOError:
  9346. App.log.error("Failed to open config file: %s" % filename)
  9347. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9348. (_("Failed to open config file"), filename))
  9349. return
  9350. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  9351. """
  9352. Loads a project from the specified file.
  9353. 1) Loads and parses file
  9354. 2) Registers the file as recently opened.
  9355. 3) Calls on_file_new()
  9356. 4) Updates options
  9357. 5) Calls new_object() with the object's from_dict() as init method.
  9358. 6) Calls plot_all() if plot=True
  9359. :param filename: Name of the file from which to load.
  9360. :type filename: str
  9361. :param run_from_arg: True if run for arguments
  9362. :param plot: If True plot all objects in the project
  9363. :param cli: run from command line
  9364. :return: None
  9365. """
  9366. App.log.debug("Opening project: " + filename)
  9367. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9368. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9369. if cli is None:
  9370. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  9371. if run_from_arg:
  9372. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9373. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9374. _("Opening FlatCAM Project file.")),
  9375. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9376. color=QtGui.QColor("gray"))
  9377. # Open and parse an uncompressed Project file
  9378. try:
  9379. f = open(filename, 'r')
  9380. except IOError:
  9381. App.log.error("Failed to open project file: %s" % filename)
  9382. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9383. (_("Failed to open project file"), filename))
  9384. return
  9385. try:
  9386. d = json.load(f, object_hook=dict2obj)
  9387. except Exception as e:
  9388. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  9389. (filename, str(e)))
  9390. f.close()
  9391. # Open and parse a compressed Project file
  9392. try:
  9393. with lzma.open(filename) as f:
  9394. file_content = f.read().decode('utf-8')
  9395. d = json.loads(file_content, object_hook=dict2obj)
  9396. except Exception as e:
  9397. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  9398. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9399. (_("Failed to open project file"), filename))
  9400. return
  9401. # Clear the current project
  9402. # # NOT THREAD SAFE # ##
  9403. if run_from_arg is True:
  9404. pass
  9405. elif cli is True:
  9406. self.delete_selection_shape()
  9407. else:
  9408. self.on_file_new()
  9409. # Project options
  9410. self.options.update(d['options'])
  9411. self.project_filename = filename
  9412. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9413. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9414. if cli is None:
  9415. self.set_screen_units(self.options["units"])
  9416. # Re create objects
  9417. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  9418. for obj in d['objs']:
  9419. def obj_init(obj_inst, app_inst):
  9420. obj_inst.from_dict(obj)
  9421. App.log.debug("Recreating from opened project an %s object: %s" %
  9422. (obj['kind'].capitalize(), obj['options']['name']))
  9423. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9424. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9425. if cli is None:
  9426. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  9427. obj['kind'].upper(),
  9428. obj['options']['name']
  9429. )
  9430. )
  9431. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  9432. self.inform.emit('[success] %s: %s' %
  9433. (_("Project loaded from"), filename))
  9434. self.should_we_save = False
  9435. self.file_opened.emit("project", filename)
  9436. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9437. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9438. if cli is None:
  9439. self.set_ui_title(name=self.project_filename)
  9440. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  9441. def propagate_defaults(self, silent=False):
  9442. """
  9443. This method is used to set default values in classes. It's
  9444. an alternative to project options but allows the use
  9445. of values invisible to the user.
  9446. :return: None
  9447. """
  9448. if silent is False:
  9449. self.log.debug("propagate_defaults()")
  9450. # Which objects to update the given parameters.
  9451. routes = {
  9452. "global_zdownrate": CNCjob,
  9453. "excellon_zeros": Excellon,
  9454. "excellon_format_upper_in": Excellon,
  9455. "excellon_format_lower_in": Excellon,
  9456. "excellon_format_upper_mm": Excellon,
  9457. "excellon_format_lower_mm": Excellon,
  9458. "excellon_units": Excellon,
  9459. "gerber_use_buffer_for_union": Gerber,
  9460. "geometry_multidepth": Geometry
  9461. }
  9462. for param in routes:
  9463. if param in routes[param].defaults:
  9464. try:
  9465. routes[param].defaults[param] = self.defaults[param]
  9466. if silent is False:
  9467. self.log.debug(" " + param + " OK")
  9468. except KeyError:
  9469. if silent is False:
  9470. self.log.debug(" ERROR: " + param + " not in defaults.")
  9471. else:
  9472. # Try extracting the name:
  9473. # classname_param here is param in the object
  9474. if param.find(routes[param].__name__.lower() + "_") == 0:
  9475. p = param[len(routes[param].__name__) + 1:]
  9476. if p in routes[param].defaults:
  9477. routes[param].defaults[p] = self.defaults[param]
  9478. if silent is False:
  9479. self.log.debug(" " + param + " OK!")
  9480. def plot_all(self, zoom=True):
  9481. """
  9482. Re-generates all plots from all objects.
  9483. :return: None
  9484. """
  9485. self.log.debug("Plot_all()")
  9486. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  9487. for obj in self.collection.get_list():
  9488. def worker_task(obj):
  9489. with self.proc_container.new("Plotting"):
  9490. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  9491. if zoom:
  9492. self.object_plotted.emit(obj)
  9493. # Send to worker
  9494. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  9495. def register_folder(self, filename):
  9496. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  9497. def register_save_folder(self, filename):
  9498. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  9499. def set_progress_bar(self, percentage, text=""):
  9500. self.ui.progress_bar.setValue(int(percentage))
  9501. def setup_shell(self):
  9502. """
  9503. Creates shell functions. Runs once at startup.
  9504. :return: None
  9505. """
  9506. self.log.debug("setup_shell()")
  9507. def shelp(p=None):
  9508. if not p:
  9509. return _("Available commands:\n") + \
  9510. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  9511. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  9512. if p not in commands:
  9513. return "Unknown command: %s" % p
  9514. return commands[p]["help"]
  9515. # --- Migrated to new architecture ---
  9516. # def options(name):
  9517. # ops = self.collection.get_by_name(str(name)).options
  9518. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  9519. def h(*args):
  9520. """
  9521. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  9522. and standalone parameters into list.
  9523. """
  9524. kwa = {}
  9525. a = []
  9526. n = len(args)
  9527. name = None
  9528. for i in range(n):
  9529. match = re.search(r'^-([a-zA-Z].*)', args[i])
  9530. if match:
  9531. assert name is None
  9532. name = match.group(1)
  9533. continue
  9534. if name is None:
  9535. a.append(args[i])
  9536. else:
  9537. kwa[name] = args[i]
  9538. name = None
  9539. return a, kwa
  9540. @contextmanager
  9541. def wait_signal(signal, timeout=10000):
  9542. """
  9543. Block loop until signal emitted, timeout (ms) elapses
  9544. or unhandled exception happens in a thread.
  9545. :param timeout: time after which the loop is exited
  9546. :param signal: Signal to wait for.
  9547. """
  9548. loop = QtCore.QEventLoop()
  9549. # Normal termination
  9550. signal.connect(loop.quit)
  9551. # Termination by exception in thread
  9552. self.thread_exception.connect(loop.quit)
  9553. status = {'timed_out': False}
  9554. def report_quit():
  9555. status['timed_out'] = True
  9556. loop.quit()
  9557. yield
  9558. # Temporarily change how exceptions are managed.
  9559. oeh = sys.excepthook
  9560. ex = []
  9561. def except_hook(type_, value, traceback_):
  9562. ex.append(value)
  9563. oeh(type_, value, traceback_)
  9564. sys.excepthook = except_hook
  9565. # Terminate on timeout
  9566. if timeout is not None:
  9567. QtCore.QTimer.singleShot(timeout, report_quit)
  9568. # # ## Block ## ##
  9569. loop.exec_()
  9570. # Restore exception management
  9571. sys.excepthook = oeh
  9572. if ex:
  9573. self.raiseTclError(str(ex[0]))
  9574. if status['timed_out']:
  9575. raise Exception('Timed out!')
  9576. def make_docs():
  9577. output = ''
  9578. import collections
  9579. od = collections.OrderedDict(sorted(commands.items()))
  9580. for cmd_, val in od.items():
  9581. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  9582. t = val['help']
  9583. usage_i = t.find('>')
  9584. if usage_i < 0:
  9585. expl = t
  9586. output += expl + '\n\n'
  9587. continue
  9588. expl = t[:usage_i - 1]
  9589. output += expl + '\n\n'
  9590. end_usage_i = t[usage_i:].find('\n')
  9591. if end_usage_i < 0:
  9592. end_usage_i = len(t[usage_i:])
  9593. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  9594. else:
  9595. extras = t[usage_i+end_usage_i+1:]
  9596. parts = [s.strip() for s in extras.split('\n')]
  9597. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  9598. for p in parts:
  9599. output += ' ' + p + '\n\n'
  9600. return output
  9601. '''
  9602. Howto implement TCL shell commands:
  9603. All parameters passed to command should be possible to set as None and test it afterwards.
  9604. This is because we need to see error caused in tcl,
  9605. if None value as default parameter is not allowed TCL will return empty error.
  9606. Use:
  9607. def mycommand(name=None,...):
  9608. Test it like this:
  9609. if name is None:
  9610. self.raise_tcl_error('Argument name is missing.')
  9611. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  9612. otherwise we will miss it and processing will silently continue.
  9613. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  9614. which is catched in exec_command and displayed in TCL shell console with red background.
  9615. Error in console is displayed with TCL trace.
  9616. This behavior works only within main thread,
  9617. errors with promissed tasks can be catched and detected only with log.
  9618. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  9619. TCL shell.
  9620. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  9621. '''
  9622. commands = {
  9623. 'help': {
  9624. 'fcn': shelp,
  9625. 'help': _("Shows list of commands.")
  9626. },
  9627. }
  9628. # Import/overwrite tcl commands as objects of TclCommand descendants
  9629. # This modifies the variable 'commands'.
  9630. tclCommands.register_all_commands(self, commands)
  9631. # Add commands to the tcl interpreter
  9632. for cmd in commands:
  9633. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  9634. # Make the tcl puts function return instead of print to stdout
  9635. self.tcl.eval('''
  9636. rename puts original_puts
  9637. proc puts {args} {
  9638. if {[llength $args] == 1} {
  9639. return "[lindex $args 0]"
  9640. } else {
  9641. eval original_puts $args
  9642. }
  9643. }
  9644. ''')
  9645. def setup_recent_items(self):
  9646. # TODO: Move this to constructor
  9647. icons = {
  9648. "gerber": "share/flatcam_icon16.png",
  9649. "excellon": "share/drill16.png",
  9650. 'geometry': "share/geometry16.png",
  9651. "cncjob": "share/cnc16.png",
  9652. "script": "share/script_new24.png",
  9653. "document": "share/notes16_1.png",
  9654. "project": "share/project16.png",
  9655. "svg": "share/geometry16.png",
  9656. "dxf": "share/dxf16.png",
  9657. "pdf": "share/pdf32.png",
  9658. "image": "share/image16.png"
  9659. }
  9660. openers = {
  9661. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  9662. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  9663. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  9664. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  9665. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  9666. "document": None,
  9667. 'project': self.open_project,
  9668. 'svg': self.import_svg,
  9669. 'dxf': self.import_dxf,
  9670. 'image': self.import_image,
  9671. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  9672. }
  9673. # Open recent file for files
  9674. try:
  9675. f = open(self.data_path + '/recent.json')
  9676. except IOError:
  9677. App.log.error("Failed to load recent item list.")
  9678. self.inform.emit('[ERROR_NOTCL] %s' %
  9679. _("Failed to load recent item list."))
  9680. return
  9681. try:
  9682. self.recent = json.load(f)
  9683. except json.scanner.JSONDecodeError:
  9684. App.log.error("Failed to parse recent item list.")
  9685. self.inform.emit('[ERROR_NOTCL] %s' %
  9686. _("Failed to parse recent item list."))
  9687. f.close()
  9688. return
  9689. f.close()
  9690. # Open recent file for projects
  9691. try:
  9692. fp = open(self.data_path + '/recent_projects.json')
  9693. except IOError:
  9694. App.log.error("Failed to load recent project item list.")
  9695. self.inform.emit('[ERROR_NOTCL] %s' %
  9696. _("Failed to load recent projects item list."))
  9697. return
  9698. try:
  9699. self.recent_projects = json.load(fp)
  9700. except json.scanner.JSONDecodeError:
  9701. App.log.error("Failed to parse recent project item list.")
  9702. self.inform.emit('[ERROR_NOTCL] %s' %
  9703. _("Failed to parse recent project item list."))
  9704. fp.close()
  9705. return
  9706. fp.close()
  9707. # Closure needed to create callbacks in a loop.
  9708. # Otherwise late binding occurs.
  9709. def make_callback(func, fname):
  9710. def opener():
  9711. func(fname)
  9712. return opener
  9713. def reset_recent_files():
  9714. # Reset menu
  9715. self.ui.recent.clear()
  9716. self.recent = []
  9717. try:
  9718. f = open(self.data_path + '/recent.json', 'w')
  9719. except IOError:
  9720. App.log.error("Failed to open recent items file for writing.")
  9721. return
  9722. json.dump(self.recent, f)
  9723. def reset_recent_projects():
  9724. # Reset menu
  9725. self.ui.recent_projects.clear()
  9726. self.recent_projects = []
  9727. try:
  9728. fp = open(self.data_path + '/recent_projects.json', 'w')
  9729. except IOError:
  9730. App.log.error("Failed to open recent projects items file for writing.")
  9731. return
  9732. json.dump(self.recent, fp)
  9733. # Reset menu
  9734. self.ui.recent.clear()
  9735. self.ui.recent_projects.clear()
  9736. # Create menu items for projects
  9737. for recent in self.recent_projects:
  9738. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9739. if recent['kind'] == 'project':
  9740. try:
  9741. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9742. # Attach callback
  9743. o = make_callback(openers[recent["kind"]], recent['filename'])
  9744. action.triggered.connect(o)
  9745. self.ui.recent_projects.addAction(action)
  9746. except KeyError:
  9747. App.log.error("Unsupported file type: %s" % recent["kind"])
  9748. # Last action in Recent Files menu is one that Clear the content
  9749. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent projects")), self)
  9750. clear_action_proj.triggered.connect(reset_recent_projects)
  9751. self.ui.recent_projects.addSeparator()
  9752. self.ui.recent_projects.addAction(clear_action_proj)
  9753. # Create menu items for files
  9754. for recent in self.recent:
  9755. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9756. if recent['kind'] != 'project':
  9757. try:
  9758. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9759. # Attach callback
  9760. o = make_callback(openers[recent["kind"]], recent['filename'])
  9761. action.triggered.connect(o)
  9762. self.ui.recent.addAction(action)
  9763. except KeyError:
  9764. App.log.error("Unsupported file type: %s" % recent["kind"])
  9765. # Last action in Recent Files menu is one that Clear the content
  9766. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  9767. clear_action.triggered.connect(reset_recent_files)
  9768. self.ui.recent.addSeparator()
  9769. self.ui.recent.addAction(clear_action)
  9770. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  9771. # self.ui.menufilerecent.set_submenu(recent_menu)
  9772. # recent_menu.show_all()
  9773. # self.ui.recent.show()
  9774. self.log.debug("Recent items list has been populated.")
  9775. def setup_component_editor(self):
  9776. # label = QtWidgets.QLabel("Choose an item from Project")
  9777. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  9778. sel_title = QtWidgets.QTextEdit(
  9779. _('<b>Shortcut Key List</b>'))
  9780. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  9781. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  9782. settings = QSettings("Open Source", "FlatCAM")
  9783. if settings.contains("notebook_font_size"):
  9784. fsize = settings.value('notebook_font_size', type=int)
  9785. else:
  9786. fsize = 12
  9787. tsize = fsize + int(fsize / 2)
  9788. # selected_text = (_('''
  9789. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  9790. #
  9791. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  9792. # The normal flow when working in FlatCAM is the following:</span></p>
  9793. #
  9794. # <ol>
  9795. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  9796. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  9797. # even dragging and dropping the files on the GUI.<br />
  9798. # <br />
  9799. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  9800. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  9801. # &nbsp;</li>
  9802. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  9803. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  9804. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  9805. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  9806. # <br />
  9807. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  9808. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  9809. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  9810. # it even if it was out of focus.<br />
  9811. # <br />
  9812. # You can change the parameters in this screen and the flow direction is like this:<br />
  9813. # <br />
  9814. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  9815. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  9816. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  9817. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  9818. # </ol>
  9819. #
  9820. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  9821. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  9822. # <strong>F3</strong>.</span></p>
  9823. #
  9824. # ''').format(fsize=fsize, tsize=tsize))
  9825. selected_text = '''
  9826. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  9827. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  9828. {s1}</span></p>
  9829. <ol>
  9830. <li><span style="font-size:{fsize}px">{s2}<br />
  9831. <br />
  9832. {s3}</span><br />
  9833. &nbsp;</li>
  9834. <li><span style="font-size:{fsize}px">{s4}<br />
  9835. &nbsp;</li>
  9836. <br />
  9837. <li><span style="font-size:{fsize}px">{s5}<br />
  9838. &nbsp;</li>
  9839. <br />
  9840. <li><span style="font-size:{fsize}px">{s6}<br />
  9841. <br />
  9842. {s7}</span></li>
  9843. </ol>
  9844. <p><span style="font-size:{fsize}px">{s8}</span></p>
  9845. '''.format(
  9846. title=_("Selected Tab - Choose an Item from Project Tab"),
  9847. subtitle=_("Details"),
  9848. s1=_("The normal flow when working in FlatCAM is the following:"),
  9849. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  9850. "using either the toolbars, key shortcuts or even dragging and dropping the "
  9851. "files on the GUI."),
  9852. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  9853. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  9854. "actions offered within the app."),
  9855. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  9856. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  9857. "SELECTED TAB will be updated with the object properties according to its kind: "
  9858. "Gerber, Excellon, Geometry or CNCJob object."),
  9859. s5=_("If the selection of the object is done on the canvas by single click instead, "
  9860. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  9861. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  9862. "the SELECTED TAB and populate it even if it was out of focus."),
  9863. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  9864. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  9865. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  9866. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  9867. "(again, done in SELECTED TAB) --> Save GCode."),
  9868. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  9869. "or through its own key shortcut: <b>F3</b>."),
  9870. tsize=tsize,
  9871. fsize=fsize
  9872. )
  9873. sel_title.setText(selected_text)
  9874. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  9875. self.ui.selected_scroll_area.setWidget(sel_title)
  9876. def setup_obj_classes(self):
  9877. """
  9878. Sets up application specifics on the FlatCAMObj class.
  9879. :return: None
  9880. """
  9881. FlatCAMObj.app = self
  9882. ObjectCollection.app = self
  9883. Gerber.app = self
  9884. Excellon.app = self
  9885. Geometry.app = self
  9886. CNCjob.app = self
  9887. FCProcess.app = self
  9888. FCProcessContainer.app = self
  9889. def version_check(self):
  9890. """
  9891. Checks for the latest version of the program. Alerts the
  9892. user if theirs is outdated. This method is meant to be run
  9893. in a separate thread.
  9894. :return: None
  9895. """
  9896. self.log.debug("version_check()")
  9897. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  9898. full_url = App.version_url + \
  9899. "?s=" + str(self.defaults['global_serial']) + \
  9900. "&v=" + str(self.version) + \
  9901. "&os=" + str(self.os) + \
  9902. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  9903. else:
  9904. # no_stats dict; just so it won't break things on website
  9905. no_ststs_dict = {}
  9906. no_ststs_dict["global_ststs"] = {}
  9907. full_url = App.version_url + \
  9908. "?s=" + str(self.defaults['global_serial']) + \
  9909. "&v=" + str(self.version) + \
  9910. "&os=" + str(self.os) + \
  9911. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  9912. App.log.debug("Checking for updates @ %s" % full_url)
  9913. # ## Get the data
  9914. try:
  9915. f = urllib.request.urlopen(full_url)
  9916. except:
  9917. # App.log.warning("Failed checking for latest version. Could not connect.")
  9918. self.log.warning("Failed checking for latest version. Could not connect.")
  9919. self.inform.emit('[WARNING_NOTCL] %s' %
  9920. _("Failed checking for latest version. Could not connect."))
  9921. return
  9922. try:
  9923. data = json.load(f)
  9924. except Exception as e:
  9925. App.log.error("Could not parse information about latest version.")
  9926. self.inform.emit('[ERROR_NOTCL] %s' %
  9927. _("Could not parse information about latest version."))
  9928. App.log.debug("json.load(): %s" % str(e))
  9929. f.close()
  9930. return
  9931. f.close()
  9932. # ## Latest version?
  9933. if self.version >= data["version"]:
  9934. App.log.debug("FlatCAM is up to date!")
  9935. self.inform.emit('[success] %s' %
  9936. _("FlatCAM is up to date!"))
  9937. return
  9938. App.log.debug("Newer version available.")
  9939. self.message.emit(
  9940. _("Newer Version Available"),
  9941. _("There is a newer version of FlatCAM available for download:\n\n") +
  9942. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  9943. _("info")
  9944. )
  9945. def on_plotcanvas_setup(self, container=None):
  9946. """
  9947. This is doing the setup for the plot area (VisPy canvas)
  9948. :param container: widget where to install the canvas
  9949. :return: None
  9950. """
  9951. if container:
  9952. plot_container = container
  9953. else:
  9954. plot_container = self.ui.right_layout
  9955. if self.is_legacy is False:
  9956. self.plotcanvas = PlotCanvas(plot_container, self)
  9957. else:
  9958. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  9959. # So it can receive key presses
  9960. self.plotcanvas.native.setFocus()
  9961. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  9962. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  9963. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  9964. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  9965. # Keys over plot enabled
  9966. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  9967. if self.defaults['global_cursor_type'] == 'small':
  9968. self.app_cursor = self.plotcanvas.new_cursor()
  9969. else:
  9970. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  9971. if self.ui.grid_snap_btn.isChecked():
  9972. self.app_cursor.enabled = True
  9973. else:
  9974. self.app_cursor.enabled = False
  9975. if self.is_legacy is False:
  9976. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  9977. else:
  9978. # will use the default Matplotlib axes
  9979. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  9980. def on_zoom_fit(self, event):
  9981. """
  9982. Callback for zoom-out request. This can be either from the corresponding
  9983. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  9984. with axes limits from the geometry bounds of all objects.
  9985. :param event: Ignored.
  9986. :return: None
  9987. """
  9988. if self.is_legacy is False:
  9989. self.plotcanvas.fit_view()
  9990. else:
  9991. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  9992. width = xmax - xmin
  9993. height = ymax - ymin
  9994. xmin -= 0.05 * width
  9995. xmax += 0.05 * width
  9996. ymin -= 0.05 * height
  9997. ymax += 0.05 * height
  9998. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  9999. def on_zoom_in(self):
  10000. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  10001. def on_zoom_out(self):
  10002. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  10003. def disable_all_plots(self):
  10004. self.report_usage("disable_all_plots()")
  10005. self.disable_plots(self.collection.get_list())
  10006. self.inform.emit('[success] %s' %
  10007. _("All plots disabled."))
  10008. def disable_other_plots(self):
  10009. self.report_usage("disable_other_plots()")
  10010. self.disable_plots(self.collection.get_non_selected())
  10011. self.inform.emit('[success] %s' %
  10012. _("All non selected plots disabled."))
  10013. def enable_all_plots(self):
  10014. self.report_usage("enable_all_plots()")
  10015. self.enable_plots(self.collection.get_list())
  10016. self.inform.emit('[success] %s' %
  10017. _("All plots enabled."))
  10018. def on_enable_sel_plots(self):
  10019. log.debug("App.on_enable_sel_plot()")
  10020. object_list = self.collection.get_selected()
  10021. self.enable_plots(objects=object_list)
  10022. self.inform.emit('[success] %s' %
  10023. _("Selected plots enabled..."))
  10024. def on_disable_sel_plots(self):
  10025. log.debug("App.on_disable_sel_plot()")
  10026. # self.inform.emit(_("Disabling plots ..."))
  10027. object_list = self.collection.get_selected()
  10028. self.disable_plots(objects=object_list)
  10029. self.inform.emit('[success] %s' %
  10030. _("Selected plots disabled..."))
  10031. def enable_plots(self, objects):
  10032. """
  10033. Disables plots
  10034. :param objects: list of Objects to be enabled
  10035. :return:
  10036. """
  10037. log.debug("Enabling plots ...")
  10038. # self.inform.emit(_("Working ..."))
  10039. for obj in objects:
  10040. if obj.options['plot'] is False:
  10041. obj.options.set_change_callback(lambda x: None)
  10042. obj.options['plot'] = True
  10043. obj.options.set_change_callback(obj.on_options_change)
  10044. def worker_task(objects):
  10045. with self.proc_container.new(_("Enabling plots ...")):
  10046. for obj in objects:
  10047. # obj.options['plot'] = True
  10048. if isinstance(obj, FlatCAMCNCjob):
  10049. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  10050. else:
  10051. obj.plot(visible=True)
  10052. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  10053. # self.plots_updated.emit()
  10054. def disable_plots(self, objects):
  10055. """
  10056. Disables plots
  10057. :param objects: list of Objects to be disabled
  10058. :return:
  10059. """
  10060. # if no objects selected then do nothing
  10061. if not self.collection.get_selected():
  10062. return
  10063. log.debug("Disabling plots ...")
  10064. # self.inform.emit(_("Working ..."))
  10065. for obj in objects:
  10066. if obj.options['plot'] is True:
  10067. obj.options.set_change_callback(lambda x: None)
  10068. obj.options['plot'] = False
  10069. obj.options.set_change_callback(obj.on_options_change)
  10070. try:
  10071. self.delete_selection_shape()
  10072. except Exception as e:
  10073. log.debug("App.disable_plots() --> %s" % str(e))
  10074. # self.plots_updated.emit()
  10075. def worker_task(objects):
  10076. with self.proc_container.new(_("Disabling plots ...")):
  10077. for obj in objects:
  10078. # obj.options['plot'] = True
  10079. if isinstance(obj, FlatCAMCNCjob):
  10080. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  10081. else:
  10082. obj.plot(visible=False)
  10083. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  10084. def toggle_plots(self, objects):
  10085. """
  10086. Toggle plots visibility
  10087. :param objects: list of Objects for which to be toggled the visibility
  10088. :return:
  10089. """
  10090. # if no objects selected then do nothing
  10091. if not self.collection.get_selected():
  10092. return
  10093. log.debug("Toggling plots ...")
  10094. self.inform.emit(_("Working ..."))
  10095. for obj in objects:
  10096. if obj.options['plot'] is False:
  10097. obj.options['plot'] = True
  10098. else:
  10099. obj.options['plot'] = False
  10100. self.plots_updated.emit()
  10101. def clear_plots(self):
  10102. objects = self.collection.get_list()
  10103. for obj in objects:
  10104. obj.clear(obj == objects[-1])
  10105. # Clear pool to free memory
  10106. self.clear_pool()
  10107. def generate_cnc_job(self, objects):
  10108. self.report_usage("generate_cnc_job()")
  10109. # for obj in objects:
  10110. # obj.generatecncjob()
  10111. for obj in objects:
  10112. obj.on_generatecnc_button_click()
  10113. def save_project(self, filename, quit_action=False, silent=False):
  10114. """
  10115. Saves the current project to the specified file.
  10116. :param filename: Name of the file in which to save.
  10117. :type filename: str
  10118. :param quit_action: if the project saving will be followed by an app quit; boolean
  10119. :param silent: if True will not display status messages
  10120. :return: None
  10121. """
  10122. self.log.debug("save_project()")
  10123. self.save_in_progress = True
  10124. with self.proc_container.new(_("Saving FlatCAM Project")):
  10125. # Capture the latest changes
  10126. # Current object
  10127. try:
  10128. self.collection.get_active().read_form()
  10129. except:
  10130. self.log.debug("There was no active object")
  10131. pass
  10132. # Project options
  10133. self.options_read_form()
  10134. # Serialize the whole project
  10135. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  10136. "options": self.options,
  10137. "version": self.version}
  10138. if self.defaults["global_save_compressed"] is True:
  10139. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  10140. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  10141. # # Write
  10142. f.write(g)
  10143. self.inform.emit('[success] %s: %s' %
  10144. (_("Project saved to"), filename))
  10145. else:
  10146. # Open file
  10147. try:
  10148. f = open(filename, 'w')
  10149. except IOError:
  10150. App.log.error("Failed to open file for saving: %s", filename)
  10151. return
  10152. # Write
  10153. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  10154. f.close()
  10155. # verification of the saved project
  10156. # Open and parse
  10157. try:
  10158. saved_f = open(filename, 'r')
  10159. except IOError:
  10160. if silent is False:
  10161. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  10162. (_("Failed to verify project file"), filename, _("Retry to save it."))
  10163. )
  10164. return
  10165. try:
  10166. saved_d = json.load(saved_f, object_hook=dict2obj)
  10167. except:
  10168. if silent is False:
  10169. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  10170. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  10171. )
  10172. f.close()
  10173. return
  10174. saved_f.close()
  10175. if silent is False:
  10176. if 'version' in saved_d:
  10177. self.inform.emit('[success] %s: %s' %
  10178. (_("Project saved to"), filename))
  10179. else:
  10180. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  10181. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  10182. )
  10183. settings = QSettings("Open Source", "FlatCAM")
  10184. lock_state = self.ui.lock_action.isChecked()
  10185. settings.setValue('toolbar_lock', lock_state)
  10186. # This will write the setting to the platform specific storage.
  10187. del settings
  10188. # if quit:
  10189. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  10190. # t.start()
  10191. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  10192. def start_delayed_quit(self, delay, filename, should_quit=None):
  10193. """
  10194. :param delay: period of checking if project file size is more than zero; in seconds
  10195. :param filename: the name of the project file to be checked periodically for size more than zero
  10196. :param should_quit: if the task finished will be followed by an app quit; boolean
  10197. :return:
  10198. """
  10199. to_quit = should_quit
  10200. self.save_timer = QtCore.QTimer()
  10201. self.save_timer.setInterval(delay)
  10202. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  10203. self.save_timer.start()
  10204. def check_project_file_size(self, filename, should_quit=None):
  10205. """
  10206. :param filename: the name of the project file to be checked periodically for size more than zero
  10207. :param should_quit: will quit the app if True; boolean
  10208. :return:
  10209. """
  10210. try:
  10211. if os.stat(filename).st_size > 0:
  10212. self.save_in_progress = False
  10213. self.save_timer.stop()
  10214. if should_quit:
  10215. self.app_quit.emit()
  10216. except Exception as e:
  10217. traceback.print_exc()
  10218. def on_plotarea_tab_closed(self, tab_idx):
  10219. widget = self.ui.plot_tab_area.widget(tab_idx)
  10220. if widget is not None:
  10221. print(widget.objectName())
  10222. if widget.objectName() == 'text_editor_tab':
  10223. print("aha")
  10224. widget.deleteLater()
  10225. self.ui.plot_tab_area.removeTab(tab_idx)
  10226. def on_options_app2project(self):
  10227. """
  10228. Callback for Options->Transfer Options->App=>Project. Copies options
  10229. from application defaults to project defaults.
  10230. :return: None
  10231. """
  10232. self.report_usage("on_options_app2project")
  10233. self.defaults_read_form()
  10234. self.options.update(self.defaults)
  10235. self.options_write_form()
  10236. # def on_options_project2app(self):
  10237. # """
  10238. # Callback for Options->Transfer Options->Project=>App. Copies options
  10239. # from project defaults to application defaults.
  10240. #
  10241. # :return: None
  10242. # """
  10243. #
  10244. # self.report_usage("on_options_project2app")
  10245. #
  10246. # self.options_read_form()
  10247. # self.defaults.update(self.options)
  10248. # self.defaults_write_form()
  10249. # def on_options_project2object(self):
  10250. # """
  10251. # Callback for Options->Transfer Options->Project=>Object. Copies options
  10252. # from project defaults to the currently selected object.
  10253. #
  10254. # :return: None
  10255. # """
  10256. #
  10257. # self.report_usage("on_options_project2object")
  10258. #
  10259. # self.options_read_form()
  10260. # obj = self.collection.get_active()
  10261. # if obj is None:
  10262. # self.inform.emit('[WARNING_NOTCL] %s' %
  10263. # _("No object selected."))
  10264. # return
  10265. # for option in self.options:
  10266. # if option.find(obj.kind + "_") == 0:
  10267. # oname = option[len(obj.kind) + 1:]
  10268. # obj.options[oname] = self.options[option]
  10269. # obj.to_form() # Update UI
  10270. # def on_options_object2project(self):
  10271. # """
  10272. # Callback for Options->Transfer Options->Object=>Project. Copies options
  10273. # from the currently selected object to project defaults.
  10274. #
  10275. # :return: None
  10276. # """
  10277. #
  10278. # self.report_usage("on_options_object2project")
  10279. #
  10280. # obj = self.collection.get_active()
  10281. # if obj is None:
  10282. # self.inform.emit('[WARNING_NOTCL] %s' %
  10283. # _("No object selected."))
  10284. # return
  10285. # obj.read_form()
  10286. # for option in obj.options:
  10287. # if option in ['name']: # TODO: Handle this better...
  10288. # continue
  10289. # self.options[obj.kind + "_" + option] = obj.options[option]
  10290. # self.options_write_form()
  10291. # def on_options_object2app(self):
  10292. # """
  10293. # Callback for Options->Transfer Options->Object=>App. Copies options
  10294. # from the currently selected object to application defaults.
  10295. #
  10296. # :return: None
  10297. # """
  10298. #
  10299. # self.report_usage("on_options_object2app")
  10300. #
  10301. # obj = self.collection.get_active()
  10302. # if obj is None:
  10303. # self.inform.emit('[WARNING_NOTCL] %s' %
  10304. # _("No object selected."))
  10305. # return
  10306. # obj.read_form()
  10307. # for option in obj.options:
  10308. # if option in ['name']: # TODO: Handle this better...
  10309. # continue
  10310. # self.defaults[obj.kind + "_" + option] = obj.options[option]
  10311. # self.defaults_write_form()
  10312. # def on_options_app2object(self):
  10313. # """
  10314. # Callback for Options->Transfer Options->App=>Object. Copies options
  10315. # from application defaults to the currently selected object.
  10316. #
  10317. # :return: None
  10318. # """
  10319. #
  10320. # self.report_usage("on_options_app2object")
  10321. #
  10322. # self.defaults_read_form()
  10323. # obj = self.collection.get_active()
  10324. # if obj is None:
  10325. # self.inform.emit('[WARNING_NOTCL] %s' %
  10326. # _("No object selected."))
  10327. # return
  10328. # for option in self.defaults:
  10329. # if option.find(obj.kind + "_") == 0:
  10330. # oname = option[len(obj.kind) + 1:]
  10331. # obj.options[oname] = self.defaults[option]
  10332. # obj.to_form() # Update UI
  10333. class ArgsThread(QtCore.QObject):
  10334. open_signal = pyqtSignal(list)
  10335. start = pyqtSignal()
  10336. if sys.platform == 'win32':
  10337. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  10338. else:
  10339. address = ('/tmp/testipc', 'AF_UNIX')
  10340. def __init__(self):
  10341. super(ArgsThread, self).__init__()
  10342. self.start.connect(self.run)
  10343. def my_loop(self, address):
  10344. try:
  10345. listener = Listener(*address)
  10346. while True:
  10347. conn = listener.accept()
  10348. self.serve(conn)
  10349. except socket.error as e:
  10350. conn = Client(*address)
  10351. conn.send(sys.argv)
  10352. conn.send('close')
  10353. # close the current instance only if there are args
  10354. if len(sys.argv) > 1:
  10355. sys.exit()
  10356. def serve(self, conn):
  10357. while True:
  10358. msg = conn.recv()
  10359. if msg == 'close':
  10360. break
  10361. self.open_signal.emit(msg)
  10362. conn.close()
  10363. # the decorator is a must; without it this technique will not work unless the start signal is connected
  10364. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  10365. @pyqtSlot()
  10366. def run(self):
  10367. self.my_loop(self.address)
  10368. class GracefulException(Exception):
  10369. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  10370. def __init__(self):
  10371. super().__init__()
  10372. def __str__(self):
  10373. return '\n\n%s' % _("The user requested a graceful exit of the current task.")
  10374. # end of file