FlatCAMApp.py 375 KB

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